[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

+46
View File
@@ -11,3 +11,49 @@ jobs:
build-and-test:
uses: GTNewHorizons/GTNH-Actions-Workflows/.github/workflows/build-and-test.yml@master
secrets: inherit
forge-functional-tests:
needs: build-and-test
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
- name: Checkout mod repo
uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Set up Java
uses: actions/setup-java@v5
with:
distribution: zulu
java-version: 8
- name: Set up Gradle
uses: gradle/actions/setup-gradle@v5
with:
validate-wrappers: true
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Accept the Minecraft EULA
run: |
mkdir -p run/server
echo "eula=true" > run/eula.txt
echo "eula=true" > run/server/eula.txt
- name: Run Forge functional tests
run: ./gradlew --build-cache --stacktrace runFunctionalTestServer
# The server runs out of process; without this a failure leaves only the counts.
- name: Upload functional test reports
if: always()
uses: actions/upload-artifact@v4
with:
name: forge-functional-test-reports
path: |
run/server/junit-out/
run/server/logs/
run/server/crash-reports/
if-no-files-found: warn
retention-days: 14
-32
View File
@@ -1,32 +0,0 @@
# ForgeMultipart
Changelog of ForgeMultipart.
### No issue
**Bump minor version**
[022b1f363e676a5](https://github.com/GTNewHorizons/ForgeMultipart/commit/022b1f363e676a5)
by Jason Mitchell *2021-05-16 17:40:32*
**Fix buildscript**
[15c1419db896c6b](https://github.com/GTNewHorizons/ForgeMultipart/commit/15c1419db896c6b)
by Jason Mitchell *2021-05-16 17:33:41*
**update gradle**
[b3c96b992fdabc5](https://github.com/GTNewHorizons/ForgeMultipart/commit/b3c96b992fdabc5)
by DreamMasterXXL *2021-03-07 20:05:11*
**Guard against meta > 15**
[ad1ad6da380dbfa](https://github.com/GTNewHorizons/ForgeMultipart/commit/ad1ad6da380dbfa)
by Jason Mitchell *2021-03-07 18:01:36*
**Update buildscripts to work**
[64776f0d32f8eb5](https://github.com/GTNewHorizons/ForgeMultipart/commit/64776f0d32f8eb5)
by Jason Mitchell *2021-03-07 18:01:12*
+21 -10
View File
@@ -1,16 +1,27 @@
ForgeMultipart
==============
An API for dynamically handling different functional parts in the one block space.
An API for dynamically handling different functional parts in the one block space, for Minecraft 1.7.10 / Forge.
This is the GT New Horizons fork.
Requirements:
* The latest version of CCL (files.minecraftforge.net/CodeChickenLib/)
* Forge
* A scala compatible IDE and project (For eclipse, download the scala eclipse plugin and right click on the project -> Add Scala Nature)
## Using the API
If you only want to use the API and not modify it:
* Download the latest dev version from files.minecraftforge.net/ForgeMultipart/
* Download the latest dev version of CCL.
* Place both mods in your /libs/ folder and link them as libraries in your IDE.
Depend on the dev artifact, for example `com.github.GTNewHorizons:ForgeMultipart:<version>:dev`, alongside GTNH
CodeChickenCore. Start at the [Java API index](docs/API.md): it lists the supported entry points with a guide and a
compiling Java example for each. You do not need Scala in your own mod to use them.
Implementation of all parts of the API should be clean and easy in Java. The minecraft multipart mod is implemented in java as a test case.
If you are rebuilding an existing integration against the Java port, read the [release notes](docs/RELEASE_NOTES.md)
first. Already compiled consumer jars keep working.
## Building
The codebase is being ported from Scala to Java. Most sources are Java now, but they still live under
`src/main/scala` so they can be joint-compiled with the Scala files that remain. Everything compiles for Java 8.
```
./gradlew build
```
Use `gradlew.bat` on Windows. The [maintainer guide](docs/migration/MAINTAINERS.md) covers the build boundaries,
the Forge functional tests and the full verification sequence. Port status and remaining work are in the
[migration status](docs/migration/README.md).
+160 -1
View File
@@ -1 +1,160 @@
apply plugin: 'scala'
import org.gradle.api.tasks.GradleBuild
import groovy.xml.XmlSlurper
apply plugin: 'scala'
SourceSet functionalTestSet
sourceSets {
functionalTestSet = create("functionalTest") {
java {
srcDir("src/functionalTest/java")
compileClasspath += sourceSets.patchedMc.output + sourceSets.main.output
}
}
}
configurations {
named(functionalTestSet.compileClasspathConfigurationName).configure {
extendsFrom(named("compileClasspath").get())
}
named(functionalTestSet.runtimeClasspathConfigurationName).configure {
extendsFrom(named("runtimeClasspath").get())
}
named(functionalTestSet.annotationProcessorConfigurationName).configure {
extendsFrom(named("annotationProcessor").get())
}
}
// FML scans classpath jars for @Mod with an ASM that predates Java 9, so every JUnit jar logs a LoaderException
// stack trace for its module-info. Repackage them into the test mod jar and keep the originals off the classpath.
def junitArtifactPrefixes = ["junit-jupiter", "junit-platform", "opentest4j", "apiguardian"]
def isJunitArtifact = { File f -> junitArtifactPrefixes.any { f.name.startsWith(it) } }
def functionalTestRuntime = configurations.named(functionalTestSet.runtimeClasspathConfigurationName)
tasks.register(functionalTestSet.jarTaskName, Jar) {
from(functionalTestSet.output)
from(functionalTestRuntime.map { cfg -> cfg.files.findAll(isJunitArtifact).collect { zipTree(it) } }) {
// META-INF/versions is the Java 9+ half of the multi-release jars, never loaded on this Java 8 server.
// Signatures do not survive repackaging; the engine is still found through META-INF/services.
exclude(
"module-info.class",
"META-INF/versions/**",
"META-INF/*.SF",
"META-INF/*.DSA",
"META-INF/*.RSA")
}
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
archiveClassifier.set("functionalTests")
archiveVersion.set("1.0")
destinationDirectory.set(layout.buildDirectory.dir("tmp"))
}
// Compile the documented consumer surface against the packaged dev jar, not main/test class directories.
def compileJavaApiExamples = tasks.register("compileJavaApiExamples", JavaCompile) {
group = "verification"
description = "Compiles the Java API examples against the dev jar without Scala libraries"
source(fileTree("src/test/java") { include("codechicken/**/examples/*.java") })
source(fileTree("src/functionalTest/java") { include("codechicken/**/examples/*.java") })
classpath = files(tasks.named("jar")) + sourceSets.main.compileClasspath.filter {
!it.name.startsWith("scala-")
}
destinationDirectory = layout.buildDirectory.dir("classes/java/apiExamples")
javaCompiler = javaToolchains.compilerFor { languageVersion = JavaLanguageVersion.of(8) }
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
options.encoding = "UTF-8"
options.annotationProcessorPath = files()
options.sourcepath = files()
options.compilerArgs.add("-proc:none")
}
tasks.named("check") { dependsOn(compileJavaApiExamples) }
def functionalTestRunProperty = "forgemultipart.withFunctionalTests"
def withFunctionalTests = providers.gradleProperty(functionalTestRunProperty).map { it.toBoolean() }.orElse(false).get()
def profileRunProperty = "forgemultipart.profileFunctionalTests"
def profileFunctionalTests = providers.gradleProperty(profileRunProperty).map { it.toBoolean() }.orElse(false).get()
def functionalTestReportDirectory = layout.projectDirectory.dir("run/server/junit-out")
def functionalTestProfileRecording = layout.projectDirectory.file("run/server/forgemultipart-baseline.jfr")
def functionalTestProfileResults = layout.projectDirectory.file("run/server/forgemultipart-profile.txt")
def addFunctionalTestsToRun = { JavaExec task ->
task.dependsOn(functionalTestSet.jarTaskName)
task.classpath(
// JUnit is repackaged into the test mod jar above.
functionalTestRuntime.map { cfg -> cfg.files.findAll { !isJunitArtifact(it) } },
tasks.named(functionalTestSet.jarTaskName))
}
tasks.register("runFunctionalTestServer", GradleBuild) {
group = "verification"
description = "Runs the Java 8 Forge server with the ForgeMultipart functional test mod"
setTasks(["runServer"])
startParameter.projectProperties.put(functionalTestRunProperty, "true")
if (profileFunctionalTests) {
startParameter.projectProperties.put(profileRunProperty, "true")
}
doFirst {
delete(functionalTestReportDirectory)
if (profileFunctionalTests) {
delete(functionalTestProfileRecording, functionalTestProfileResults)
}
}
doLast {
def reports = fileTree(functionalTestReportDirectory).matching { include("TEST-*.xml") }.files
if (reports.isEmpty()) {
throw new GradleException("ForgeMultipart functional tests produced no JUnit XML report")
}
int tests = 0
int failures = 0
int errors = 0
int skipped = 0
def failed = []
reports.each { report ->
def suite = new XmlSlurper(false, false).parse(report)
tests += suite.@tests.toInteger()
failures += suite.@failures.toInteger()
errors += suite.@errors.toInteger()
skipped += suite.@skipped.toString().isEmpty() ? 0 : suite.@skipped.toInteger()
suite.testcase.each { testcase ->
if (!testcase.failure.isEmpty() || !testcase.error.isEmpty()) {
failed << "${testcase.@classname}.${testcase.@name}"
}
}
}
def summary = "Forge functional tests: ${tests} tests, ${tests - failures - errors - skipped} passed, " +
"${failures} failures, ${errors} errors, ${skipped} skipped"
logger.lifecycle(summary)
failed.each { logger.lifecycle(" FAILED ${it}") }
def stepSummary = System.getenv("GITHUB_STEP_SUMMARY")
if (stepSummary) {
new File(stepSummary) << "### ${summary}\n" + failed.collect { "- FAILED `${it}`\n" }.join()
}
if (tests == 0 || failures > 0 || errors > 0) {
throw new GradleException("ForgeMultipart functional tests failed: ${summary}")
}
if (profileFunctionalTests
&& (!functionalTestProfileRecording.asFile.isFile() || !functionalTestProfileResults.asFile.isFile())) {
throw new GradleException("ForgeMultipart profile produced incomplete output")
}
}
}
if (withFunctionalTests) {
tasks.withType(JavaExec).configureEach { task ->
if (task.name == "runServer") {
addFunctionalTestsToRun(task)
if (profileFunctionalTests) {
task.jvmArgs(
"-XX:+FlightRecorder",
"-XX:StartFlightRecording=filename=forgemultipart-baseline.jfr,settings=profile,dumponexit=true")
task.systemProperty(profileRunProperty, "true")
}
}
}
}
+26
View File
@@ -3,3 +3,29 @@
plugins {
id 'com.gtnewhorizons.gtnhconvention'
}
tasks.test {
useJUnitPlatform()
testLogging {
events("failed")
exceptionFormat = "full"
}
// Gradle prints nothing on success, so a green run never says how much ran.
afterSuite { desc, result ->
if (desc.parent != null) {
return
}
def summary = "Unit tests: ${result.testCount} tests, ${result.successfulTestCount} passed, " +
"${result.failedTestCount} failed, ${result.skippedTestCount} skipped"
logger.lifecycle(summary)
def stepSummary = System.getenv("GITHUB_STEP_SUMMARY")
if (stepSummary) {
new File(stepSummary) << "### ${summary}\n"
}
}
}
tasks.named('compileScala') {
// Zinc does not invalidate joint-compiled Java annotations when Tags.VERSION changes.
scalaCompileOptions.force = true
}
+13 -5
View File
@@ -1,8 +1,18 @@
// Add your dependencies here
dependencies {
testImplementation(platform("org.junit:junit-bom:5.11.4"))
testImplementation("org.junit.jupiter:junit-jupiter")
testRuntimeOnly("org.lwjgl.lwjgl:lwjgl:2.9.4-nightly-20150209")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
functionalTestImplementation(platform("org.junit:junit-bom:5.11.4"))
functionalTestImplementation("org.junit.jupiter:junit-jupiter")
functionalTestImplementation("org.junit.platform:junit-platform-engine")
functionalTestImplementation("org.junit.platform:junit-platform-launcher")
functionalTestImplementation("org.junit.platform:junit-platform-reporting")
implementation("com.github.GTNewHorizons:CodeChickenCore:1.4.22:dev")
compileOnly("com.cardinalstar.cubicchunks:CubicChunks1710:v0.1.8-alpha:dev")
compileOnly("com.cardinalstar.cubicchunks:CubicChunks1710:v0.1.22-alpha:dev")
compileOnly("com.github.GTNewHorizons:Angelica:2.2.32:dev")
runtimeOnlyNonPublishable("com.github.GTNewHorizons:Hodgepodge:2.7.216:dev")
compileOnly("com.github.GTNewHorizons:Postea:1.2.7:dev") {transitive = false}
@@ -10,6 +20,4 @@ dependencies {
exclude group: 'com.github.GTNewHorizons', module: 'CodeChickenCore'
}
compileOnly("com.github.GTNewHorizons:GTNHLib:0.11.54:dev")
// devOnlyNonPublishable("com.github.GTNewHorizons:Angelica:2.2.32:dev")
devOnlyNonPublishable("io.github.legacymoddingmc:unimixins:0.1.23:dev")
}
+136
View File
@@ -0,0 +1,136 @@
# ForgeMultipart Java API
Start here when integrating with ForgeMultipart for **Minecraft 1.7.10 / Forge**. This describes the `algent/java`
migration branch. Its new APIs are implemented and tested but do not yet have a minimum published dependency version.
Use a dev artifact containing the methods you need; source Javadocs are packaged with the sources artifact.
Consumers can use the Java surface without importing Scala types. FMP itself still needs Scala at runtime. A
Scala-authored mod can adopt the Java API without converting the rest of its code to Java.
Every guide links a compiling example. `./gradlew compileJavaApiExamples` (also run by `check`) compiles all of them
as Java 8 against the packaged dev jar with no `scala-*` library on the classpath, so a documented example that
needs Scala fails the build. Add new documented examples to the test or functional-test `examples` packages.
**Rebuilding an existing mod against this branch? Read the [release notes](RELEASE_NOTES.md) first.** Shipped binaries
keep working, but recompiling has three classes of break, and the trait-composition one compiles cleanly and changes
behavior at runtime. Use the [consumer migration checklist](api/MIGRATION_CHECKLIST.md) to carry a source change through
runtime validation, release and target-pack adoption.
## Direct calls and optional integration
The intended consumer API uses direct typed public calls, without reflection, private-field mixins or Scala
companion lookup. Reuse existing entry points where they cover the task. For optional support, isolate FMP-typed
code in a compatibility class loaded only after mod-presence and supported-version checks; test absent and present
mod loading. Reflection snippets in older guides are legacy interoperability options, not the migration target.
Existing reflective binaries remain supported until consumer release and pack adoption.
## Choose a guide
| Task | API and guide |
| --- | --- |
| Define, place, persist, synchronize and remove a custom part | `TMultiPart`, `canPlacePart`, `addPart`, `remPart` - [end-to-end custom-part lifecycle](api/CUSTOM_PARTS.md) |
| Register block converters | `registerConverter(IPartConverter)` - [registration, state ownership and committed lifecycle](api/BLOCK_CONVERTERS.md) |
| Register part factories during mod initialization | `registerPartFactory(IPartFactory2, String...)` - [factory timing, payload ownership and migration](api/PART_REGISTRATION.md) |
| Find the factory registered for a part type | `getPartFactory(String)` - [lookup ownership and Schematica reflection migration](api/FACTORY_LOOKUP.md) |
| Enumerate microblock materials by numeric ID | `materialCount()`, `materialName(int)`, `getMaterial(int)` - [material enumeration](api/MATERIAL_ENUMERATION.md) |
| Read a microblock material's block and metadata | `BlockMicroMaterial.block()`, `meta()` - [typed GuideNH query, identity and overrides](api/MATERIAL_ACCESS.md) |
| Create a microblock with the requested material and side | `MicroblockGenerator.create(MicroblockClass, int, boolean)` - [construction, material traits and GuideNH migration](api/MICROBLOCK_CREATION.md) |
| Call generated tile capabilities from Java | `TileMultipart`, `IRedstoneTile` and ordinary interfaces - [safe compilation and raw-trait pitfalls](api/TILE_TRAIT_ACCESS.md) |
| Add aggregate or lifecycle behavior to generated multipart tiles | `registerTrait(marker, trait)` - [custom Java tile traits, stable capabilities and transformer constraints](api/CUSTOM_TILE_TRAITS.md) |
| Refresh slots after a stored part changes shape | `refreshPartSlots(TMultiPart)` - [ownership, equality and notification responsibilities](api/TILE_TRAIT_ACCESS.md#refreshing-a-changed-slot-mask) |
| Refresh the tile inventory after a stored part changes its inventory size | `refreshInventorySlots()` - [mapping, scope and AE2 migration](api/TILE_TRAIT_ACCESS.md#refreshing-inventory-slots) |
| Add material-specific behavior to generated microblocks | `registerTrait(String)` and `IGeneratedMaterial` - [illuminated Java extension, compilation and side contracts](api/MICROBLOCK_EXTENSIONS.md) |
| Access built-in saws and change their cutting strength | `MicroblockProxy.sawStone()` and `ItemSaw.setHarvestLevel(int)` - [state, rendering and Iguana migration](api/SAW_STRENGTH.md) |
| Read/index/search a tile's parts | `jPartList()` - [part collection ownership and order](api/PART_TRAVERSAL.md#collection-ownership-and-ordering) |
| Run callbacks only on parts still owned by the tile | `forEachPart(Consumer)` - [callback and override behavior](api/PART_TRAVERSAL.md#callback-behavior) |
| Rebuild parts on an already prepared composite tile | `loadPartList(Collection)` - [part loading](api/PART_LOADING.md) |
| Select client/server tile capabilities before preparing state and loading | `MultipartGenerator.generateCompositeTile(TileEntity, Iterable, boolean)` - [staged generation and reflection migration](api/COMPOSITE_GENERATION.md) |
| Build and render an uninstalled client tile from saved multipart NBT | `MultipartHelper.createPreviewTileFromNBT(World, NBTTagCompound)` - [client preview lifecycle and reflection migration](api/CLIENT_PREVIEW.md) |
| Assign stored parts during reconstruction, without binding or notifications | `setPartList(List)` - [storage assignment](api/PART_LOADING.md#storage-assignment) |
| Test a candidate against a selected collection of parts | `testOcclusion(Collection, candidate)` - [occlusion queries and generated hooks](api/OCCLUSION.md) |
| Test two groups of bounding boxes directly | `NormalOcclusionTest.testBoxes(Iterable, Iterable)` - [box-versus-box queries](api/OCCLUSION.md#box-versus-box-queries) |
| Read FMP's global render registration ID | `TileMultipart.getRenderID()` - [render-ID meaning, lifecycle and setter](api/RENDER_ID.md) |
| Find which part a ray-trace hit struck | `BlockMultipart.hitPartIndex(MovingObjectPosition)` - [index meaning, staleness and GT5U migration](api/HIT_PART.md) |
| Inspect an existing tile or converted placeholder with a named result | `getOrConvertTileResult(World, BlockCoord)` - [conversion outcomes and placement lifecycle](api/TILE_CONVERSION.md) |
| Add or remap multipart button attachment orientations | `ButtonPart.setOrientation(int, ForgeDirection)` - [metadata, face mapping and Et Futurum migration](api/BUTTON_ORIENTATIONS.md) |
| Read a custom button's orientation metadata from its attachment face | `ButtonPart.metaForSide(int)` - [live inverse lookup and ProjectRed migration](api/BUTTON_ORIENTATIONS.md#reading-orientation-metadata) |
Each guide explains ownership, lifecycle, legacy replacements and limitations. The loading/setter APIs are advanced reconstruction operations; ordinary placement and
removal should use the existing world APIs below.
## Existing Java entry points
These entry points already exist. The links lead to their source/Javadocs; detailed migration guides and checks for
compilation without Scala are still pending in these areas. A Java-typed overload can still require Scala on the
compile classpath for overload resolution, as the [loading guide](api/PART_LOADING.md#overrides-and-reflection) explains.
| Area | Starting points |
| --- | --- |
| Construct a server composite tile from parts, or restore saved multipart NBT | [MultipartHelper](../src/main/scala/codechicken/multipart/MultipartHelper.java): `createTileFromParts(Iterable)`, `createTileFromNBT(World, NBTTagCompound)` |
| Register microblock materials | [MicroMaterialRegistry](../src/main/scala/codechicken/microblock/MicroMaterialRegistry.java) and [BlockMicroMaterial](../src/main/scala/codechicken/microblock/BlockMicroMaterial.java) |
| Register generated tile traits or pass-through interfaces | [MultipartGenerator](../src/main/scala/codechicken/multipart/MultipartGenerator.java); see [custom tile-trait authoring](api/CUSTOM_TILE_TRAITS.md) and [safe capability access](api/TILE_TRAIT_ACCESS.md) |
New API examples use Java 8 language/library features. The source path `src/main/scala` also contains Java classes
because of the current joint-compilation layout; it does not imply that those APIs require Scala source in a consumer.
## Supported API and internal hooks
Public visibility alone does not make a method a consumer entry point. Scala's former package-private methods are
public in bytecode. Source Javadocs now mark the following audited implementation hooks **Internal FMP**; keep
consumer code on the public operations in the right column. These markers change no visibility, descriptor or
behavior and do not deprecate or authorize removing a method. Trait callbacks and generated overrides still run.
| Internal hooks | Consumer operation or responsibility |
| --- | --- |
| `TileMultipart.addPart_impl`, `addPart_do`, `writeAddPart` | Place through `TileMultipart.addPart(world, pos, part)`; use [part loading](api/PART_LOADING.md) for prepared reconstruction |
| `TileMultipart.remPart_impl` | Remove through `tile.remPart(part)` on the server and retain the returned tile |
| `TileMultipart.partAdded`, `partRemoved` | Lifecycle callbacks for trait overrides; callers use placement/removal APIs |
| `TileMultipart.from`, `copyFrom`, `loadFrom`, `setValid` | FMP composite transitions; use [staged generation](api/COMPOSITE_GENERATION.md) and [loading](api/PART_LOADING.md) for consumer reconstruction |
| `MicroMaterialRegistry.setupIDMap`, `calcMaxCuttingStrength` | FMP initializes IDs and cutting strength; register materials at initialization and read the resulting values |
| `MicroMaterialRegistry.loadIcons` | FMP dispatches client texture callbacks; override the supported `IMicroMaterial.loadIcons()` material callback |
| `MicroMaterialRegistry.writeIDMap`, `readIDMap` | FMP's whole-map handshake; part packets use `writeMaterialID` / `readMaterialID` for individual IDs |
The registry's matching companion methods carry the same internal marker. This is a bounded consumer audit,
not a claim that every other public member is a supported API. See [TileMultipart's Javadocs](../src/main/scala/codechicken/multipart/TileMultipart.java)
and [registry Javadocs](../src/main/scala/codechicken/microblock/MicroMaterialRegistry.java) for method-specific details.
Four advanced methods remain supported because consumers use them directly:
- **`bindPart(part)`** updates capability caches through generated overrides. It does not insert the part, change
its tile binding or perform placement/notifications. The legacy OpenComputers integration clears a print part's old
slot entries before calling it to populate a changed slot mask. A repeated call does not clear obsolete slots and
may append entries in other trait caches. Use `refreshPartSlots` for that migration; full reconstruction uses
`loadPartList`.
- **`refreshPartSlots(part)`** replaces OpenComputers' direct generated-array mutation. Generated slotted tiles clear
equal cached entries and invoke the virtual bind chain once; base tiles do nothing. It leaves ownership, storage,
validation and notifications to the caller. See the [slot-refresh contract](api/TILE_TRAIT_ACCESS.md#refreshing-a-changed-slot-mask).
- **`refreshInventorySlots()`** replaces AE2's direct `TIInventoryTile.rebuildSlotMap()` call. Generated inventory
tiles recompute their flattened slot mapping from the inventories they already track; other tiles do nothing. It
does not bind parts or notify. See [refreshing inventory slots](api/TILE_TRAIT_ACCESS.md#refreshing-inventory-slots).
- **`internalPartChange(part)`** sends local `onPartChanged` callbacks through the retained `operate` hook. The base
traversal captures list order, visits only parts still bound to the receiving tile, and excludes parts equal to the
changed part using `part.equals(p)`. Null broadcasts to all eligible parts. Detached or transferred parts are skipped.
Callback failures stop traversal and propagate. ProjectRed deliberately handles dirty state,
packets and external neighbors separately; this method does none of those. `notifyPartChange` also performs world
update/neighbor/lighting notifications when needed.
No reflection is needed to call any of these methods. `operate` and `getOrConvertTile2` retain their documented legacy
contracts and Java replacements; neither receives an internal-only marker. Removing those bridges still requires
consumer and internal migration gates. The [consumer audit](migration/COMPATIBILITY.md#api-boundary-audit)
records the checked source calls and validation.
## Legacy entry points and project status
Deprecated Scala-facing entry points remain callable, with their descriptors and supported override dispatch retained.
Follow the method-specific guide: a Java sibling is not automatically a replacement override hook, and reflection
must select the intended parameter types when a method is overloaded.
Remaining work, consumer adoption and the Scala-removal gates are tracked in the [migration status](migration/README.md).
| Need | Document |
| --- | --- |
| What is complete and what comes next? | [Migration status](migration/README.md) |
| Which consumers need changes, releases and pack adoption? | [Consumer adoption ledger](migration/COMPATIBILITY.md#java-api-adoption-ledger) |
| Which binary names, reflective lookups and runtime contracts must survive? | [ABI inventory and consumer audit](migration/COMPATIBILITY.md) |
| What has been tested and what still needs a client/pack run? | [Migration status](migration/README.md), [manual release checks](migration/MANUAL_CHECKS.md) |
| Why is some Scala or older Java syntax retained? | [Build boundaries](migration/MAINTAINERS.md#build-and-runtime-boundaries), [compiler constraints](migration/MAINTAINERS.md#retained-compiler-constraints) |
+142
View File
@@ -0,0 +1,142 @@
# Release notes - the Java port
ForgeMultipart's implementation moved from Scala to Java. This page is for mod authors who depend on FMP.
**If you ship a compiled jar and do not rebuild it, nothing here affects you.** Every runtime interface, method
descriptor and reflective name the audited consumers use was preserved deliberately, and the retained Scala bridges
still link. Intentional behavior differences are listed in the [divergence ledger](migration/DIVERGENCES.md).
**If you rebuild against the new dev jar, read on.** Recompiling is the case that breaks, and one class of break is
silent. There are three kinds, in descending order of how badly they fail. The [consumer migration checklist](api/MIGRATION_CHECKLIST.md)
turns the cases below into concrete compile, runtime, release and pack-adoption gates.
## 1. Linkage errors: the generated tile traits
Six types were Scala traits, which compile to an interface plus a `$class` helper. They are now concrete Java classes
in the dev jar. Forge's transformer rewrites them back into interfaces at load time, so **existing binaries are
unaffected** - they already call interface methods, and the runtime type is still an interface.
Source compiled against the untransformed dev jar is the problem. `javac` and `scalac` see a class, emit
`invokevirtual` or `getfield`, and the JVM then rejects it against the runtime interface.
| Type | Recompiled call fails with |
| --- | --- |
| `scalatraits.TRedstoneTile` | `IncompatibleClassChangeError` |
| `scalatraits.TSlottedTile` | `NoSuchFieldError` on `v_partMap` |
| `scalatraits.TTileChangeTile` | `IncompatibleClassChangeError` |
| `scalatraits.TFluidHandlerTile` | `IncompatibleClassChangeError` |
| `scalatraits.TRandomDisplayTickTile` | `IncompatibleClassChangeError` |
| `TileMultipartClient` | `IncompatibleClassChangeError` |
**The fix is to target the stable capability interface instead of the raw dev-jar class.** Note the package: the
types that break are in `codechicken.multipart.scalatraits`, the replacements are not. The existing
`IRedstoneTile.openConnections` and `TileMultipart.partMap` contracts work on both old and new FMP; the new
`TileMultipart.refreshPartSlots` requires an FMP release containing the Java API.
| Instead of | Use |
| --- | --- |
| `scalatraits.TRedstoneTile.openConnections(side)` | `codechicken.multipart.IRedstoneTile.openConnections(side)` |
| casting to `scalatraits.TSlottedTile` and writing `v_partMap` | `codechicken.multipart.TileMultipart.refreshPartSlots(part)` |
| reading `scalatraits.TSlottedTile.partMap(slot)` | `codechicken.multipart.TileMultipart.partMap(slot)` |
`refreshPartSlots` clears value-equal entries from the live array and dispatches the bind chain once. Keep your own
validation and state change before the call, and your sound, notification, description and scheduling order after it.
See [stable tile capability access](api/TILE_TRAIT_ACCESS.md) for the full contract and worked examples.
### Known affected consumers
Confirmed still present on each project's default branch:
| Mod | Call site | Member |
| --- | --- | --- |
| ProjectRed | `transmission/redwires.scala` | `TRedstoneTile.openConnections` |
| OpenComputers | `integration/fmp/PrintPart.scala` | `TSlottedTile.v_partMap` |
`TTileChangeTile`, `TFluidHandlerTile` and `TRandomDisplayTickTile` have no known consumer references.
## 2. Silent behavior changes: recompiled Scala trait composition
**This is the dangerous one - it compiles cleanly and does the wrong thing at runtime.**
A Java interface cannot supply a Scala trait's class supertype or its linearization. When a superclass method and an
interface default both apply, the superclass wins. So recompiling `extends TMultiPart with TCuboidPart` silently
selects `TMultiPart`'s empty methods instead of the cuboid implementations, and your part loses its collision boxes
rather than failing to build.
Where the implementation is now an interface default, forward explicitly:
| Trait | What to do when recompiling |
| --- | --- |
| `TCuboidPart` | Extend `JCuboidPart`, or forward subparts, collision boxes and breaking rendering to its statics |
| `TNormalOcclusion` | Combine `NormalOcclusionTest.apply(this, other)` with the intended super chain explicitly. Audit existing `super.occlusionTest` calls: they no longer route through the old trait |
| `TIconHitEffects` | Forward `addHitEffects` and `addDestroyEffects` to `IconHitEffects` |
| `TItemMultiPart` | Forward `onItemUse` to `JItemMultiPart`; the inherited `Item` method otherwise wins |
| `TRandomUpdateTick` | Implement `onWorldJoin` as `TickScheduler.loadRandomTick(this)` |
| `TScheduledPacketPart` | Forward `read` to `TScheduledPacketPart.readMask(this, packet)` |
| `ScratchBitSet` | Implement both methods and the storage accessors, and initialize storage explicitly |
Previously compiled calls into **retained** `$class` bridges still link; this applies only to recompilation.
## 3. Compile errors: Scala source syntax
These fail loudly at build time, so they are the safe category. Existing bytecode keeps working.
- An `object` used as a value needs `X$.MODULE$` where the companion is retained. Static forwarders alone do not
supply a singleton value.
- Application sugar becomes an explicit `.apply(...)`, e.g. `NormalOcclusionTest.apply(...)`.
- `x.partList(i)` becomes `x.partList.apply(i)`.
- Scala property assignment needs the Java `_$eq(...)` method, e.g. `renderID`, `loadingWorld`, microblock `shape`.
- `Tuple2` members typed `Boolean` in Scala arrive as `Object` and need a cast.
- Scala 2.11 will not adapt a lambda to `Function1[_, BoxedUnit]`, so `operate { p => ... }` needs an explicit
`AbstractFunction1`. Prefer the Java `forEachPart(Consumer)` entry point.
- The Face, Corner, Edge and Post bounds facades are Java static array getters now, so they need an extra empty
argument list before the index.
- `ByteCodeReader.advance(length)(value)` becomes `advance(length, value)`.
- `ASMImplicits` no longer provides implicit or value-class syntax; call the retained `$extension` entry points
explicitly.
- `ASMMixinFactory` constructor and `construct` arguments need an explicit Scala `Seq`, not varargs.
One runtime trap that is not a compile error: **do not call a side-only Scala object's static facade from common
Java.** `MultipartProxy.postInit()` exists in the raw jar but inherits `@SideOnly(CLIENT)`, so Forge strips the
forwarder on a dedicated server and the call fails with `NoSuchMethodError`. Call `MultipartProxy$.MODULE$.postInit()`
as the Scala reference did.
## Adopting the Java API
You do not have to convert your mod to Java. A Scala mod can call the Java surface directly, and the documented
entry points compile with no Scala on the classpath. Start at the [Java API index](API.md).
Direct typed calls are the intended end state. Reflection snippets in older guides are legacy interoperability
options, not the migration target. For optional integration, isolate FMP-typed code in a compatibility class loaded
only after mod-presence and version checks, and test both the absent and present cases.
Saved multipart client previews can use `MultipartHelper.createPreviewTileFromNBT` plus the existing
`MultipartRenderer.renderWorldBlock`; see the [client preview guide](api/CLIENT_PREVIEW.md). Custom `IPartFactory2`
implementations opt in through `createPartForClientPreview` when they can build their client variant from saved NBT.
## Will I have to migrate again?
No, if you migrate to the documented Java surface. That is the point of shipping it alongside the old one.
FMP still retains Scala storage, runtime and compatibility bridges. A later release removes them, and that release
removes the **Scala-shaped** entry points: `partList(): scala.collection.Seq`, `operate(Function1)`,
`registerParts(Seq)`, the `$class` trait helpers and the `MODULE$` companions. The Java siblings that replace them
stay. So:
| What you depend on | What the Scala-removal release does to it |
| --- | --- |
| The documented Java surface: `jPartList`, `forEachPart`, `registerPartFactory`, `refreshPartSlots`, `IRedstoneTile` | Unaffected. One migration, done. |
| The Scala-shaped entry points | Removed. This is the migration being asked for now. |
| A raw dev-jar class such as `scalatraits.TRedstoneTile` | Wrong target. See below. |
**The one way to migrate twice is to aim at the wrong type.** If a rebuild fails on `TRedstoneTile` and the fix looks
like "cast to the class the dev jar actually shows", that produces the `IncompatibleClassChangeError` in section 1 and
still has to be redone against `IRedstoneTile` afterwards. Always target the stable capability interface, never the
raw class the dev jar exposes for a transformed trait.
Two honest limits on that guarantee. It covers the surface that is documented here and in the
[compatibility audit](migration/COMPATIBILITY.md); a dependency in neither can still be caught out, which is
why removal waits on evidence of adoption in released consumer jars rather than on source patches alone. And FMP's own
source layout will change when Scala goes, since the Java sources currently live under `src/main/scala` for joint
compilation. That moves no class, package, descriptor or reflective name, so it is invisible to consumers; only
source-attachment paths in an IDE change.
+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.
+905
View File
@@ -0,0 +1,905 @@
# Downstream compatibility: ABI inventory and consumer audit
Status: installed-jar and source refresh 2026-10-16 against GTNH `2.9.0-RC-2`; older dated snapshots are kept
below as history. Read this before changing any compatibility surface. It has two parts, answering two different
questions.
- **Part 1, the ABI inventory**, answers "what must still link?" It is a constant-pool scan of every mod jar in a
real pack, not a source search.
- **Part 2, the consumer audit**, answers the harder question: "what behavior do real consumers expect after they
have linked?" It covered all 27 ForgeMultipart consumers in the supplied GTNH daily `2026-08-25+700` instance, plus
UtilitiesInExcess as the planned Extra Utilities replacement. The `2.9.0-RC-2` refresh adds ThaumicEnergistics
as a 28th installed consumer and GT5U's new ProjectRed wire recoloring path.
Intentional differences from the reference belong in the [divergence ledger](DIVERGENCES.md), and the
consumer-facing summary of what breaks on rebuild is in the [release notes](../RELEASE_NOTES.md).
# Part 1 - Downstream ABI inventory
Method: constant-pool scan of every mod jar in a real pack, not a source search. Bytecode is the only oracle that
covers reflection strings, closed-source consumers, and mods whose published source does not match their release jar.
GitHub code search was deliberately not used; it indexes default branches only and silently omits results.
Scanned: GTNH `2.9.0-RC-2`, 240 mod jars (`ForgeMultipart-1.7.16.jar` itself excluded). Reproduce with
`tools/AbiScan.java`; frozen baselines in `src/test/fixtures/abi/gtnh-2.9.0-rc2-consumers.txt` (current) and
`gtnh-daily-678-consumers.txt` (original `2026-08-14+678` inventory).
```
java tools/AbiScan.java <instance>/.minecraft/mods ForgeMultipart
```
Requires a JDK 17+ single-file source launch. Re-run after public-API changes and diff against the frozen baseline;
any member that disappears from the port but appears in the baseline is a linkage break in a shipping mod.
The RC-2 scan was resolved against this branch's compiled classes: every inherited type, other type and member
resolves to a non-private declaration, or to an inherited Minecraft member. The one static exception is
`scalatraits.TSlottedTile.v_partMap()`, a runtime-generated trait accessor covered by `ForgeEnvironmentSmokeTest`.
## Totals
| Category | `+678` | `2.9.0-RC-2` |
| --- | ---: | ---: |
| Consumer jars | 27 of 240 | 28 of 240 |
| Types extended or implemented downstream | 35 | 35 |
| Referenced members with exact descriptors | 255 | 268 |
| Other referenced types | 76 | 80 |
| Reflective string constants | 20 | 9 |
Every `+678` member, inherited-type and other-type row is still present. The changes are:
- **GuideNH `1.3.41`** replaced its 17-string reflection with 28 direct member references, most already linked by other consumers, including
`MultipartGenerator$.generateCompositeTile(TileEntity, scala.collection.Iterable, boolean)`,
`TileMultipart.loadParts(scala.collection.Iterable)`, `MicroblockGenerator$.create` and `Microblock.shape_$eq(B)`.
This matches the [source findings](#guidenh); the reflective contracts remain for older GuideNH jars.
- **GT5U `5.09.54.205`** gained a ProjectRed wire recoloring path: `BlockMultipart.reduceMOP(MovingObjectPosition):
scala.Tuple2`, `TileMultipart.partMap(int)`, `TSlottedPart.getSlotMask()` and `TMultiPart.getType()`.
- **AE2 `rv3-beta-1080`** links `JCuboidPart.bind(TileMultipart)`, the `super.bind` call from its host-refresh fix.
- **ThaumicEnergistics `1.7.64-GTNH`** is a new consumer through one `Class.forName` string.
## Consumers by weight
Ranked by number of classes in the jar that touch `codechicken/multipart` or `codechicken/microblock`.
| Classes | Jar |
| ---: | --- |
| 142 | ProjRed-4.12.47-GTNH |
| 38 | extrautilities-1.2.12 |
| 19 | OpenComputers-1.12.64-GTNH |
| 18 | ProjectBlue-1.2.11-GTNH |
| 7 | appliedenergistics2-rv3-beta-1080-GTNH |
| 7 | buildcraft-compat-7.1.22 |
| 5 | ForgeRelocationFMP-0.2.0, gregtech-5.09.54.205 |
| 4 | Galacticraft-3.4.34-GTNH, ThaumicTinkerer-2.12.33, WR-CBE-1.7.12, chisel-2.17.34-GTNH |
| 3 | IguanaTweaksTConstruct-2.7.12, WitchingGadgets-1.8.51-GTNH, guidenh-1.3.41 |
| 2 | BloodArsenal-1.5.12, Botania-1.13.37-GTNH, Waila-1.19.34, matter-manipulator-0.1.61-GTNH |
| 1 | BiomesOPlenty, BloodMagic-1.9.14, Natura-2.8.24, Schematica-1.12.6-GTNH, TConstruct-1.14.118-GTNH, ae2fc-1.5.113-gtnh, endercore-0.5.15, etfuturum-2.6.60-GTNH, thaumicenergistics-1.7.64-GTNH |
Two distinct consumer shapes:
- **Java consumers** (extrautilities, AE2, chisel, WitchingGadgets, ThaumicTinkerer, buildcraft-compat, gregtech,
matter-manipulator, and the long tail) use the Java-facing API: `MultiPartRegistry.registerParts(IPartFactory, String[])`,
`registerConverter`, `BlockMicroMaterial`, `MicroMaterialRegistry.registerMaterial`, `TileMultipart.jPartList()`,
`addPart`, `remPart`, `canAddPart`. None of these need Scala.
- **Scala consumers** (ProjRed, OpenComputers, ProjectBlue, ForgeRelocationFMP) mix in ForgeMultipart traits and call
the generated `$class` static helpers directly. These are the constraint on Scala removal.
## Load-bearing Scala surface
Everything in this section must keep its exact descriptor, or a named consumer fails to link.
### Trait `$class` helpers (8 classes, 16 static methods)
| Helper | Methods used | Consumers |
| --- | --- | --- |
| `TCuboidPart$class` | `$init$`, `drawBreaking`, `getCollisionBoxes`, `getSubParts` | ForgeRelocationFMP, OpenComputers, ProjRed, ProjectBlue |
| `TIconHitEffects$class` | `$init$`, `addDestroyEffects`, `addHitEffects` | ForgeRelocationFMP, OpenComputers, ProjRed |
| `TNormalOcclusion$class` | `$init$`, `occlusionTest` | ForgeRelocationFMP, OpenComputers, ProjRed |
| `JIconHitEffects$class` | `$init$`, `getBreakingIcon` | ForgeRelocationFMP, OpenComputers, ProjRed |
| `TFacePart$class` | `$init$`, `solid`, `redstoneConductionMap` | OpenComputers, ProjRed, ProjectBlue |
| `TItemMultiPart$class` | `$init$`, `getHitDepth`, `onItemUse` | ProjRed |
| `Saw$class` | `$init$`, `getMaxCuttingStrength` | ProjRed |
| `TEdgePart$class` | `$init$` | OpenComputers |
`JPartialOcclusion$class` is not retained: it has **no** downstream caller in the pack. The two consumers that
touch `JPartialOcclusion` (ForgeRelocationFMP, WitchingGadgets) only call
`getPartialOcclusionBoxes()Ljava/lang/Iterable;`, which remains. The eight helpers above are the ones that matter.
### Companion object singletons (17 `MODULE$` fields read downstream)
`MultiPartRegistry$`, `TileMultipart$`, `MultipartGenerator$`, `NormalOcclusionTest$`, `RedstoneInteractions$`,
`MicroMaterialRegistry$`, `MicroblockGenerator$`, `MicroblockRender$`, `BlockMicroMaterial$`, `ItemMicroPart$`,
`CornerMicroClass$`, `EdgeMicroClass$`, `FaceMicroClass$`, `HollowMicroClass$`,
`handler/MultipartProxy$`, `handler/MultipartSaveLoad$`, `handler/MicroblockProxy$`.
Each must keep a public static `MODULE$` field of its own type plus the instance methods used on it.
### Members with Scala types in their descriptors (8 total)
| Descriptor | Consumers |
| --- | --- |
| `TileMultipart.partList()Lscala/collection/Seq;` | OpenComputers, ProjRed, AE2, extrautilities, guidenh |
| `NormalOcclusionTest$.apply(Lscala/collection/Traversable;Lscala/collection/Traversable;)Z` | ForgeRelocationFMP, OpenComputers |
| `MultiPartRegistry$.registerParts(Lcodechicken/multipart/MultiPartRegistry$IPartFactory2;Lscala/collection/Seq;)V` | ProjRed |
| `MultiPartRegistry$.registerParts(Lscala/Function2;Lscala/collection/Seq;)V` | ForgeRelocationFMP |
| `MicroMaterialRegistry.getIdMap()[Lscala/Tuple2;` | extrautilities |
| `MultipartGenerator$.generateCompositeTile(Lnet/minecraft/tileentity/TileEntity;Lscala/collection/Iterable;Z)Lcodechicken/multipart/TileMultipart;` | guidenh (`2.9.0-RC-2`; previously reflective only) |
| `TileMultipart.loadParts(Lscala/collection/Iterable;)V` | guidenh (`2.9.0-RC-2`; previously reflective only) |
| `BlockMultipart.reduceMOP(Lnet/minecraft/util/MovingObjectPosition;)Lscala/Tuple2;` | gregtech (new in `2.9.0-RC-2`) |
GT5U reads `reduceMOP`'s `_1()` as the boxed `Integer` part index and ignores `_2()`. The port keeps the exact
static and companion descriptors, and `BlockMultipartCharacterizationTest` pins the boxed index and rebased hit.
`BlockMultipart.hitPartIndex` is the Java replacement for the index; see the [guide](../api/HIT_PART.md) and the
adoption ledger.
The Scala-typed surface is small. `TileMultipart.jPartList()Ljava/util/List;` is already the more
widely used accessor (ProjectBlue, WitchingGadgets, buildcraft-compat, extrautilities, gregtech, matter-manipulator),
so the Java-first collection API mostly exists already and the Scala overloads are a thin retained shell.
The port supplies `NormalOcclusionTest.testBoxes(java.lang.Iterable, java.lang.Iterable)` for the box-list
contract. Both old `apply(Traversable, Traversable)` entries remain, with deprecations pointing to the Java entry.
The shipping ForgeRelocationFMP/OpenComputers companion calls still require their exact descriptor until adoption;
see the [migration guide](../api/OCCLUSION.md#box-versus-box-queries) and consumer ledger.
`MultiPartRegistry.registerPartFactory(IPartFactory2, String...)` now provides the Java registration entry without
Scala overload resolution. Both `registerParts(IPartFactory2, Seq)` entries are deprecated; all eight existing
registration descriptors remain. ProjectRed's sequence and ForgeRelocationFMP's function companion calls still need
their bridges until release/adoption. See the [registration guide](../api/PART_REGISTRATION.md).
`IDWriter` has **zero** downstream references, so its Scala function accessors were not retained.
## Reflective consumers
These fail at runtime, not at link time, so ABI tooling will not catch a break. In `2.9.0-RC-2`, 9 string
constants across:
- `Schematica-1.12.6-GTNH` - `TileMultipart`, `TMultiPart`, `MultiPartRegistry$`, `MultipartGenerator$`, `MicroblockClass`.
- `Galacticraft-3.4.34-GTNH` - `TileMultipart`, `MicroMaterialRegistry`, `BlockMicroMaterial`.
- `Waila-1.19.34` - `BlockMultipart`.
- `AE2`, `ae2fc`, `thaumicenergistics-1.7.64-GTNH` - `TileMultipart`, loaded with `Class.forName` to register Waila
providers.
- `etfuturum-2.6.60-GTNH` - `codechicken.multipart.minecraft.ButtonPart`.
`guidenh-1.3.20` in `+678` was the broadest reflective consumer, with 17 strings: `MultipartGenerator`/`MultipartGenerator$`,
`MultipartHelper`/`MultipartHelper$`, `MultipartRenderer`/`MultipartRenderer$`, `TileMultipart`,
`TileMultipartClient`, `MicroblockClient`, `Microblock`, `MicroblockClass`, `MicroblockGenerator$`,
`BlockMicroMaterial`/`BlockMicroMaterial$`, `MicroMaterialRegistry`/`MicroMaterialRegistry$`, `BlockMultipart`.
`guidenh-1.3.41` in RC-2 has none; it links the same members directly.
Note that both the class and its `$` companion are named in several cases, so renaming or removing a companion
object breaks these even where no bytecode reference exists.
The port offers `MultipartHelper.createPreviewTileFromNBT` to replace Schematica's private registry map,
microblock construction, Scala collection, generator and loader reflection as one all-or-nothing preview operation.
The lower-level `MultiPartRegistry.getPartFactory(String): IPartFactory2` remains available for specialized callers.
Existing private fields, companions and descriptors remain for released consumers until adoption.
`ButtonPart.setOrientation(int, ForgeDirection): void` now replaces Et Futurum's four reflective array writes and
keeps the two direction maps consistent; [guide](../api/BUTTON_ORIENTATIONS.md). The existing public mutable static
`metaSideMap` and `sideMetaMap` fields retain their exact names, types and modifiers for old releases. Removing or
narrowing them still waits for a migrated Et Futurum release, target-pack adoption and a fresh reflective-source scan.
`ItemSaw.setHarvestLevel(int): void` now replaces Iguana's private-field write; [guide](../api/SAW_STRENGTH.md).
The existing private `harvestLevel: int` field remains for old releases and shares storage with the setter. It loses
only `ACC_FINAL`, which makes the supported mutation explicit and keeps reflective writes working. Removal still
waits for an Iguana release, target-pack adoption and a fresh scan.
## Compatibility retention rules
1. Scala removal follows released-consumer adoption and retirement of internal Scala users.
2. Keep `registerScalaTrait`, ScalaSignature decoding and the external-trait fixtures covering
`MicroblockGenerator.registerTrait`. Third-party Scala traits are not internal-only: ProjRed's
`LightMicroMaterial$` registers `mrtjp.projectred.illumination.LightMicroblock`, a compiled Scala trait with a
`$class` helper, so `ASMMixinFactory.registerTrait` parses its ScalaSignature. Removing that path breaks
ProjRed's illuminated microblocks until a migrated release ships.
3. Preserve the listed 8 `$class` helpers, 17 `MODULE$` singletons and 8 Scala-typed descriptors until their removal
gates pass. Absence from that list alone is not permission to delete a bridge; check source and reflective use too.
4. Verify reflective member lookups separately; constant-pool strings do not establish which members are selected.
## Historical GuideNH reflective surface, from source
This section describes older supported releases, not current GuideNH source or the `1.3.41` jar shipped in
`2.9.0-RC-2`. Commit `4a0cd02e` (2026-09-16, included in tags `1.3.33` onward) removed FMP reflection and the
private-material accessor mixin. Current source
still calls the generator companions and Scala collection APIs directly; see the [current findings](#guidenh).
The constraints below remain relevant to old jars until target-pack adoption is verified.
The constant-pool scan can see the names guidenh reflects on but not the members it looks up. This section is read
from the checked-out source at `6137525`, in
`src/main/java/com/hfstudio/guidenh/integration/forgemultipart/ForgeMultipartHelpers.java`. **None of this is visible
to the ABI diff**; a break here is silent until a user opens a guide page.
The dispatch helper is `invokeStaticOrSingletonMethod(class, companion, method, args...)`. It tries a **static** method
on the plain class first, and only on `INVOCATION_MISSING` falls back to reading `companion.MODULE$` and invoking the
method on it. So for most entries the companion is a fallback. The exceptions below are the ones that matter.
| Owner | Member reflected on | Reached via |
| --- | --- | --- |
| `MultipartHelper` | `createTileFromNBT(World, NBTTagCompound)` | static; companion is fallback |
| `MultipartRenderer` | `renderWorldBlock(IBlockAccess, int, int, int, Block, int, RenderBlocks)` | static; companion is fallback |
| `MultipartGenerator` | `generateCompositeTile(TileEntity, scala.collection.Iterable, boolean)` | **companion only for the Scala descriptor**; new static Java-Iterable entry is additive |
| `BlockMicroMaterial` | `register(material)`, plus a constructor of arity 2 `(Block, int)` or 1 `(Block)` | static; companion is fallback |
| `MicroMaterialRegistry` | `getMaterial(int)` | static; companion is fallback |
| `MicroblockGenerator$` | `create(MicroblockClass, int, boolean)` | GuideNH explicitly selects the companion, matched by exact parameter types; static Java replacement exists |
| `TileMultipart` | `partList()`, `partList_$eq(scala.collection.Seq)`, `loadParts(...)`, `notifyTileChange()`, `markRender()` | instance |
| `Microblock` | `microClass()`, `material()`, `shape()` | instance |
| `TMultiPart` | `getDrops()` | instance |
| `BlockMicroMaterial` | `block()`, `meta()` | instance; absent from general `IMicroMaterial` |
Types used only for `isInstanceOf`: `BlockMultipart`, `TileMultipart`, `TileMultipartClient`, `Microblock`,
`MicroblockClient`, `BlockMicroMaterial`.
### Three constraints this adds
1. **`MultipartGenerator$.MODULE$` is load-bearing through reflection.** `generateCompositeTile` is `private[multipart]`
in Scala, so no static forwarder is emitted on `MultipartGenerator` and guidenh's static attempt always misses. It
reaches the method only through the companion. A port that keeps the class but drops the companion, or
promotes the method to a public static and removes it from the companion, breaks guidenh silently.
The port adds `MultipartGenerator.generateCompositeTile(TileEntity, java.lang.Iterable, boolean)` while
retaining the exact companion Scala descriptor/body. GuideNH's old Scala sequence is not assignable to the new
Java parameter, so its existing matcher still falls back to the companion. Both old and new reflective contracts
are tested; migration requires a Java parts collection. See the [guide](../api/COMPOSITE_GENERATION.md).
2. **`MicroblockGenerator$.create` is matched by exact parameter types**, including `pts[0].getName()` string-compared
against `"codechicken.microblock.MicroblockClass"`. That pins `create(MicroblockClass, int, boolean)` on the
companion and pins `MicroblockClass`'s fully qualified name. Widening a parameter or renaming the class breaks the
lookup even though every call site still links.
The existing static `MicroblockGenerator.create(MicroblockClass, int, boolean)` now has a
[guide and compiling example](../api/MICROBLOCK_CREATION.md). Both exact reflective entries are tested; no API
shape or production method body changes were needed. GuideNH must change its explicitly selected owner and receiver
before it stops using the companion. Release/adoption, shape-setter override checks and client previews remain gates.
3. **`TileMultipart.partList_$eq(scala.collection.Seq)` is reflectively load-bearing.** The port supplies
`setPartList(java.util.List)` and `loadPartList(java.util.Collection)`, while retaining the exact legacy setter and
loader descriptors and override dispatch. Dropping the old setter in favor of the Java method would still break
guidenh invisibly. Exact and assignability-based reflective tests cover both legacy contracts. `resolvePartList` also falls back to a public *field*
named `partList`, which never existed - Scala emits the field private - so that path is dead in the reference too.
`MultipartHelper$` is retained on the strength of the fallback path alone: the static is found first today, so the
companion is never reached in practice. That is a weaker justification than the two "companion only" entries above,
but the cost of keeping a four-method forwarder is negligible against a silent break.
GuideNH's private `BlockMicroMaterial.block: Block` and `meta: int` fields remain unchanged for its accessor mixin.
Existing public virtual `block()` / `meta()` now have a [typed query guide](../api/MATERIAL_ACCESS.md) and regression
coverage; no descriptor or method body changed. The mixin reads constructor fields whereas direct calls honor
subclass overrides, as the old reflective fallback already did. Remove the consumer's mixin only when adopting the
typed query; FMP field removal still waits for released-consumer adoption.
# Part 2 - Source-level consumer audit
## Bottom line
The Java conversion cannot be treated as a set of independent class translations. Downstream code depends on five
connected contracts:
1. **The generated composite tile architecture.** Parts cause `TileMultipart` subclasses to acquire Scala traits,
Java traits, and arbitrary pass-through interfaces. AE2, ProjectRed, Extra Utilities, WR-CBE,
WitchingGadgets, ForgeRelocationFMP, and UtilitiesInExcess all exercise this architecture.
2. **Scala-emitted binary shapes.** ProjectRed, OpenComputers, ProjectBlue, and ForgeRelocationFMP call generated
trait `$class` helpers and companion `MODULE$` objects. Java consumers also use Scala-shaped APIs such as
`partList(): scala.collection.Seq` and `getIdMap(): scala.Tuple2[]`.
3. **Multipart state and lifecycle.** Consumers do more than add parts. They inspect `partMap`, mutate/rebuild slot
maps, move the live tile object, call `onMoved`, remove and reload parts, trigger part/tile notifications, and
make deliberate choices about description packets.
4. **World, NBT, and packet formats.** The container `parts` list, each part's `id`, core microblock fields and part
type strings are an interchange format used by builders, schematic tools, movers, HUD mods, and save/load code.
Material numeric IDs and their packet encoding are also shared outside FMP.
5. **Names that are not in ordinary linkage.** Schematica reaches a private Scala-mangled field, Et Futurum mutates
static arrays, older GuideNH releases mix into private fields, Iguana reflects a saw field, and several mods load FMP classes
and companions by string. A clean ABI diff alone will miss these breaks.
The safest first Java release is therefore **Java-maintainable implementation with the bounded Scala compatibility
shell retained**. Removing the Scala runtime is a separate coordinated migration, not the end of this source port.
## Coverage and method
The supplied instance was rescanned with `tools/AbiScan.java` before reading source:
- scanner visited 241 mod JARs, one of which was excluded as ForgeMultipart itself;
- 27 consumer JARs;
- 35 downstream-extended or implemented FMP types;
- 255 referenced FMP members with exact descriptors;
- 76 other referenced FMP types;
- 20 class-name/reflection strings.
Those structural totals are unchanged from the frozen `+678` inventory. The consumer versions changed, but no new
binary API family appeared. The compatibility audit covers active consumer binaries, including Extra Utilities,
and the supplied source checkouts. It records required types/members, reflection contracts, factories, converters,
part subclasses, tile access, registry access, NBT, packets, rendering, occlusion, redstone and movement behavior.
Where source checkouts are available, important call sites were traced through the owning code instead of counting imports.
The 2026-10-16 refresh rescanned GTNH `2.9.0-RC-2` (above) and traced every new or changed row to consumer source.
The new consumer, ThaumicEnergistics, was read at `83c405d0bee3` (`1.7.66-GTNH`). Its only FMP reference
appeared in `1.7.62-GTNH`, and `ModuleWaila.java` is unchanged since the installed `1.7.64-GTNH` tag.
This gives full coverage of the current pack's known source and binary consumers. It does not claim that an arbitrary
future mod, a runtime-generated script, or an unpublished patched JAR cannot contain another reflective use. The ABI
scanner should remain a release gate for exactly that reason.
`ForgeRelocation` itself is not the source of `ForgeRelocationFMP`; both repositories are needed and both are now
present. Only the plugin is one of the FMP consumers.
### Current source references (2026-10-16)
Diffed every Java/Scala file that references FMP at either end, between the 2026-09-21 heads and the current
heads. Only three consumers changed such files:
- **GT5U**: `gregtech/api/util/ColoredBlockContainer.java` gained `ProjectRedWireContainer` (details in the
[GT5U row](#narrow-consumers-still-real-contracts)).
- **ProjectRed**: `transmission/redwires.scala` and `bundledwires.scala` add `recolour(int)` to insulated wires and
bundled cables, plus part-update key `11`. It uses only FMP members ProjectRed already linked: `markDirty`, the
part write stream, `notifyPartChange` and `markRender`. This is the target of GT5U's recoloring.
- **ProjectBlue**: `ControlPanelRenderer.java` changed label spacing only; its FMP use is unchanged.
All other changed checkouts touched no FMP-referencing file. The September note that only GuideNH and AE2 had
changed still holds for that window. Extra Utilities is the unchanged non-Git 1.2.12. No physical-client run was
performed.
| Checkout | Inspected HEAD | 2026-09-21 HEAD |
| --- | --- | --- |
| AE2FluidCraft-Rework | `c7ec5b0c8b5f` | `6e8dd013bd4e` |
| Applied-Energistics-2-Unofficial | `c690fbc273be` | `fdedc3a8f023` |
| BiomesOPlenty | `fc7f1f6392a1` | same |
| BloodArsenal | `890824be106a` | same |
| BloodMagic | `10a36f6413b8` | `6776676ef209` |
| Botania | `3f62d4b8fe7c` | `c802a448e4f4` |
| BuildCraftCompat | `79e02803be32` | same |
| Chisel | `d08e48b73ba5` | `3d3260cd71b8` |
| EnderCore | `1998218128c7` | same |
| Et-Futurum-Requiem | `1944927eecd1` | `65407a439b57` |
| ForgeRelocation | `21da7aae0e6e` | same |
| ForgeRelocationFMP | `49a810b8c63b` | same |
| Galacticraft | `ff4c5c87ba21` | `fbdc41b97e81` |
| GT5-Unofficial | `1a9469a13228` | `fe3606a12547` |
| GuideNH | `99785342eff2` | `16f142417df1` |
| IguanaTweaksTConstruct | `2bc09889d3e2` | same |
| MatterManipulator | `dbc15f55a031` | `4d9bc003f193` |
| Natura | `4f88c0665928` | same |
| OpenComputers | `1e4559ff5f24` | `a3ac18595179` |
| ProjectBlue | `28abef1385cb` | `c01a5e769643` |
| ProjectRed | `b29f404eaa05` | `e173952e96a4` |
| Schematica | `3b03ee937953` | same |
| ThaumicEnergistics | `83c405d0bee3` | new |
| ThaumicTinkerer | `e4c8acdd4fa9` | same |
| TinkersConstruct | `644373000cdc` | `8f6e2496f792` |
| UtilitiesInExcess | `3e107a1fe9bc` | same |
| waila | `f998f9ebfe09` | same |
| WirelessRedstone-CBE | `9dfb913b4880` | same |
| WitchingGadgets | `adf174f552f9` | `663bad20ac24` |
## Cross-cutting compatibility map
| Contract | Consumers that make it load-bearing | What must survive |
| --- | --- | --- |
| Part factory/converter registration | ProjectRed, Extra Utilities, OpenComputers, AE2, BuildCraftCompat, ForgeRelocationFMP, Chisel, ThaumicTinkerer, WR-CBE, WitchingGadgets, ProjectBlue, UtilitiesInExcess | Java `IPartFactory`/`IPartFactory2`, converters, the Scala `Function2` and `Seq` overloads, stable type strings, client/server construction |
| Dynamic composite tiles | ProjectRed, Extra Utilities, AE2, ForgeRelocationFMP, WR-CBE, WitchingGadgets, UtilitiesInExcess; GuideNH and Schematica reconstruct them | Trait-bit selection, generated subclass caching, pass-through interfaces, client/server selection, promotion of an existing tile |
| External Scala trait generation | ProjectRed illuminated microblocks | `MicroblockGenerator.registerTrait`, ScalaSignature decoding, `$class` helper handling, correct trait initialization and dispatch |
| Tile collections and slot state | ProjectRed, Extra Utilities, OpenComputers, AE2, ProjectBlue, GT5U, BuildCraftCompat, WitchingGadgets, MatterManipulator, GuideNH | `partList(): Seq`, `jPartList(): List`, ordering, `partMap(int)`, mutable `TSlottedTile.v_partMap`, `bindPart`, slot-map rebuilds |
| Capability-cache refresh | OpenComputers `PrintPart.toggleState` | Supported `TileMultipart.bindPart` dispatch, caller-cleared old slot entries, no implicit list insertion or part binding |
| Local part-change notification | ProjectRed `RedstoneGatePart.onOutputChange` | Supported `TileMultipart.internalPartChange`, equality filtering and `operate` dispatch; caller retains packet/dirty/external-neighbor policy |
| Placement/removal/replacement | Most custom-part mods | `getTile`/`getOrConvertTile`, `canPlacePart`, `canAddPart`, `canReplacePart`, `addPart`, `remPart`, binding and notifications in their current order |
| Move lifecycle | ForgeRelocationFMP, MatterManipulator | A live `TileMultipart` can be detached/reinserted, coordinates rewritten, then `onMoved`; render, dirty, lighting, and description synchronization remain coherent |
| Occlusion and geometry | ProjectRed, Extra Utilities, OpenComputers, AE2, ForgeRelocationFMP, Chisel, WR-CBE, WitchingGadgets, UtilitiesInExcess | Normal and partial occlusion, collision/subpart boxes, `PartMap` numbering, Java iterable adapters, Scala `Traversable` overload |
| Redstone and connectivity | ProjectRed, Extra Utilities, OpenComputers, ProjectBlue, AE2, WR-CBE | `IRedstonePart` family, `TRedstoneTile`, `RedstoneInteractions`, face/edge/center maps, neighbor and part-change propagation |
| Micro-material registry | Extra Utilities, ProjectRed, ProjectBlue, AE2, BuildCraftCompat, Chisel, material-only integrations, UtilitiesInExcess | Stable material names, integer IDs, remapping, packet ID encoding, `getIdMap(): Tuple2[]`, block/meta access, material behavior hooks |
| Multipart save/load | Extra Utilities, ProjectRed, OpenComputers, BuildCraftCompat, MatterManipulator, GuideNH, Schematica, Waila, UtilitiesInExcess | Tile `parts` list, per-part `id`, factory lookup, `save`/`load` ordering, microblock fields, unknown/invalid-part behavior |
| Description/update packets | Every substantial custom part integration | `writeDesc`/`readDesc`, keyed part packets, `sendDescUpdate`, `sendDescPacket`, material packet IDs, render and neighbor notification behavior |
| Hit-to-part reduction | GT5U `ColoredBlockContainer` | Static `BlockMultipart.reduceMOP(MovingObjectPosition): scala.Tuple2`, boxed `Integer` `_1()` matching `jPartList()` order for an `ExtendedMOP` from `RayTracer.retraceBlock`; Java replacement `hitPartIndex` |
| Reflection/mixins | Older GuideNH releases, Schematica, Et Futurum, Galacticraft, Waila, AE2/AE2FC/ThaumicEnergistics, Iguana | Exact class/companion/member/field names and, where stated below, exact parameter and field types; current GuideNH uses direct calls |
## Consumer findings
### ProjectRed - deepest current consumer
ProjectRed is not merely an optional integration. Wires, framed wires, bundled wires, gates, lamps, buttons, pipes,
solar panels, and fabricated gates are FMP parts. Its 141 touching classes dominate the installed binary surface.
- Its parts mix `TMultiPart` with `TCuboidPart`, `TFacePart`, `TSlottedPart`, `TNormalOcclusion`,
`TIconHitEffects`, redstone interfaces, and microblock hollow-connect interfaces. The emitted classes directly call
Scala trait `$class` helpers.
- Item placement uses `TItemMultiPart`; registries use both `IPartFactory` and `IPartFactory2`, including the
Scala-`Seq` registration descriptor.
- Connectivity is built on exact `PartMap` face/edge/center numbering and repeated `partMap` queries across the same
and neighboring tiles. Redstone propagation uses `RedstoneInteractions` and casts generated tiles to
`scalatraits.TRedstoneTile` for `openConnections`.
- Parts rely on lifecycle callbacks and their ordering: `onAdded`, `onRemoved`, `onPartChanged`,
`onNeighborChanged`, `onChunkLoad`, `onWorldJoin`, scheduled ticks, `notifyPartChange`, `markDirty`, and
`markRender`.
- Framed wires persist material names and use `materialID`, `materialName`, `getMaterial`, packet material IDs, and
`ItemMicroPart.create`. Their fit calculation temporarily changes their own occlusion bounds and calls
`tile.canReplacePart(this, this)`.
- Part-owned NBT and packet fields include `connMap`, `side`, `orient`, `shape`, `mat`, and type-specific data. FMP
must keep treating these tags as opaque and must continue calling part save/load and packet hooks exactly once in
the established order.
- `LightMicroMaterial` implements `MicroblockGenerator.IGeneratedMaterial` and registers the third-party Scala trait
`LightMicroblock` with `MicroblockGenerator.registerTrait`. Generated microblocks must actually acquire that trait;
it supplies dynamic halo rendering and computes light from `tile.partList`.
- ProjectRed also uses `MultipartSaveLoad.loadingWorld`, `MultipartProxy.block`, vanilla multipart part classes,
microblock class companions, saw traits, and the material highlight renderer extension.
**Migration consequence:** ProjectRed is the acceptance test for the complete architecture: Scala trait ingestion,
trait linearization, tile and microblock code generation, redstone tile traits, core lifecycle, rendering, packets,
and the micro-material system. A launch-only smoke test is inadequate; illuminated microblocks, gates, face/framed
wires, and routed pipes need functional fixtures.
### Extra Utilities 1.2.12 - active supported consumer
Extra Utilities remains in the supported compatibility target. UtilitiesInExcess is its intended replacement;
approval to switch that target and adoption of the replacement in the pack are still pending. Preserve the current
consumer's required APIs, saved-data behavior and integration coverage until both gates pass.
Required compatibility spans several FMP subsystems:
- It registers generated-tile pass-through interfaces for `IAntiMobTorch`, pipe/cosmetic/filter pipe interfaces,
node, inventory, liquid, and energy node interfaces, plus CoFH `IEnergyHandler`. Composite tiles must expose these
interfaces and dispatch to the correct part.
- Transfer pipes and nodes are multipart factories/converters. They use face/slot traits, neighbor-tile callbacks,
hollow connections, `TRedstoneTile`, `RedstoneInteractions`, part lists/maps, and part-change notifications.
- Custom parts include the magnum torch, fence, wall, sphere, pipe jackets, and several microblock-derived shapes.
They exercise normal/partial occlusion, icon hit effects, `PartMetaAccess`, `MicroblockRender`, and client/server
factories.
- Connected-texture and colored/full-bright micro-materials subclass `BlockMicroMaterial` and participate in
material rendering. Fences and walls add their own pass-through interfaces.
- NEI recipes and item enumeration consume `MicroMaterialRegistry.getIdMap()` as `scala.Tuple2[]`, use
`MicroRecipe`, saw cutting strength, material names, and `ItemMicroPart` creation.
- Some paths use `jPartList`; others use `partList().toIterator()`. Both collection views and stable ordering are
required even though the mod's implementation language is Java.
The jar is sufficient to establish behavior, while the exact JAR's constant pool remains the authority for
names and descriptors. Obfuscated Minecraft method names should not be treated as source-quality naming evidence.
**Migration consequence:** Extra Utilities covers almost every Java-facing extension seam and is the strongest test
that Java wrappers still compose into the same generated tile. UtilitiesInExcess does not make this compatibility
burden disappear until existing worlds and the old mod have been retired.
### OpenComputers - generated slot state is part of the effective API
OpenComputers converts its cable and 3D print blocks to parts and registers `oc` cable/print factories.
- `CablePart` mixes cuboid, slotted, hollow-connect, normal-occlusion, icon-effect, and OC network-environment
behavior. Network join/separate is driven from part lifecycle callbacks.
- Network traversal locates cable parts through `TileMultipart.partList`. Connection checks combine FMP normal
occlusion boxes, solid face parts, and exact `PartMap.face(...).mask` values.
- `PrintPart` mixes cuboid, edge, face, slotted, normal occlusion, and redstone traits. Its shape and slot mask change
at runtime.
- When a print toggles shape, it casts the generated tile to `scalatraits.TSlottedTile`, directly clears every
matching entry in `v_partMap`, and calls `tile.bindPart(this)` to rebuild its slots. `v_partMap` field shape and
`bindPart` behavior are therefore externally load-bearing, not private implementation details in practice.
- Placement uses `getOrConvertTile`, `canAddPart`, and `addPart`; complexity limits are calculated across the Scala
`partList`. Print redstone input also folds over that list.
**Migration consequence:** a Java slot-map rewrite must retain a binary and behavioral bridge for `TSlottedTile`,
including its public generated state. Test a print whose on/off shapes occupy different slots next to a cable and a
face part.
### ProjectBlue - Java parts built on Scala shim bases
ProjectBlue defines tiny Scala bridge bases (`JFacePart`, `JCuboidFacePart`, `JCenterPart`) so most of its FMP code
can be Java. Its active multipart is the bundled-redstone control panel.
- The bridge bases inherit `TFacePart`, `TCuboidPart`, and `TSlottedPart`, so their generated `$class` calls remain
binary dependencies.
- Control panels register an `IPartFactory`, place through `canPlacePart`/`addPart`, remove through `remPart`, and
send part description updates.
- Bundled/redwire connectivity repeatedly queries `partMap` using exact face, edge, and center indices and uses
`RedstoneInteractions` for vanilla/FMP power.
- The panel resolves its cover material by stable micro-material name and item representation. Its own persistent
fields are opaque part data.
- Its edit network identifies a target part by world coordinates plus index in `jPartList`; list order is therefore
observable over the network.
**Migration consequence:** preserve trait bridges, part ordering, `PartMap`, redstone semantics, and stable material
name lookup. A control-panel edit packet is a useful ordering regression test.
### Applied Energistics 2
AE2's cable bus is a full multipart integration, not just visual compatibility.
- `CableBusPart` is a Java cuboid part with normal occlusion, masked redstone, and `AEMultiTile`; AE2 dynamically
registers `AEMultiTile` and layer interfaces as pass-through interfaces.
- `PartRegistry` constructs registered AE2 parts through AE2's combined-instance helper. The FMP integration acts as
both part factory and block converter.
- Placement/conversion uses `getOrConvertTile`, `canAddPart`, and `addPart`. Code traverses the Scala `partList`
iterator.
- Occlusion is checked both directly with `NormalOcclusionTest` and by asking `tile.canAddPart` with an AE2
`NormallyOccludedPart` probe.
- When a generated tile implements `TIInventoryTile`, AE2 calls `rebuildSlotMap()` from `notifyNeighbors()`, after
its cable bus inventory size may have changed. `TileMultipart.refreshInventorySlots()` is the supported replacement.
- AE2's Waila path and AE2 Fluid Craft load `TileMultipart` by name to register multipart HUD providers.
- Since `4548d13f0` (2026-09-12), `CableBusPart.bind(TileMultipart)` calls `super.bind` then refreshes hosted
parts through `CableBusContainer.updatePartHostInfo`. Host changes and world join also refresh those references.
Loading and composite expansion/reduction must dispatch through the virtual `bind` hook, with the new tile already
visible through `tile()`, without restarting the parts during replacement. The port retains this behavior;
`TileMultipartLoadingTest` covers consumer host refresh through successive replacements.
- That commit also makes `CableBusPart.addPart` reject placement when `canAddPart` fails, using the existing FMP
occlusion path. No new FMP entry point is required; the Scala part-list dependency remains.
**Migration consequence:** preserve dynamic pass-through interfaces and generated tile inventory traits, not only
the `CableBusPart` class ABI. Test a cable bus sharing a block with an inventory-bearing part and an occluding cover.
### BuildCraftCompat
BuildCraftCompat serializes multipart blocks for builders and reconstructs them later.
- It identifies `MultipartProxy.block`, walks `jPartList`, calls each part's `save`, and records the part type.
- Restore calls `MultiPartRegistry.loadPart(type, tag)`, then uses `canPlacePart`/`addPart`.
- Its microblock schematic validates the saved material name through `MicroMaterialRegistry.getMaterial`.
- It understands and rotates FMP's own saved type IDs for face, corner, edge, post, hollow, torch, lever, button,
and redstone-torch parts.
**Migration consequence:** registry lookup, part `save`/`load`, core type IDs, material names, and placement validation
are a world-data contract. A builder round trip containing every built-in Minecraft part and microblock shape should
be a golden test.
### ForgeRelocationFMP
The plugin registers `rfmp_frame`, a frame-block converter, an `IFrame` pass-through interface, and an FMP tile
mover.
- `FramePart` mixes `TCuboidPart`, `TNormalOcclusion`, and `TIconHitEffects`. Its special fit test temporarily exposes
one face occlusion box, calls `canReplacePart(this, this)`, and combines another part's normal boxes, partial boxes,
and collision boxes through the Scala `NormalOcclusionTest` overload.
- Frame placement requires an existing multipart tile and uses `canPlacePart`/`addPart`.
- The mover removes the live `TileMultipart`, moves the original block and tile object, rewrites `xCoord/yCoord/zCoord`,
reinserts it, and calls `onMoved()` in the post-move hook.
**Migration consequence:** this is a direct test of Scala trait helpers, Scala factory overloads, mixed occlusion,
pass-through interfaces, and live tile movement. `onMoved` must reestablish every coordinate-sensitive/generated-tile
invariant without replacing the tile object.
### Chisel
Chisel registers its blocks as micro-materials and adds a `chisel_torch` factory/converter. `PartChiselTorch`
subclasses FMP's `TorchPart`, including its constructors, load/read/write behavior and static side mapping. Placement
uses tile conversion, fit checks, and `addPart`; Chisel also supplies a full-bright material implementation.
**Migration consequence:** the Minecraft-part classes are extension bases, not internal examples. Keep protected
state, constructors, packet/NBT hooks, and static orientation tables source- and binary-compatible.
### ThaumicTinkerer
ThaumicTinkerer registers block micro-materials and factories/converters for candle and nitor parts. The parts extend
`McMetaPart`; the candle participates in random display ticks. They rely on FMP meta-part persistence, placement,
render hooks, and factory type dispatch.
**Migration consequence:** preserve `McMetaPart` subclass semantics and random-display capability composition.
### Wireless Redstone CBE
WR-CBE registers transmitter, receiver, and jammer parts and pass-through interfaces for wireless tile APIs.
- Its Java parts use `JItemMultiPart`, `JCuboidPart`, face/redstone, normal/partial occlusion, icon effects, and
micro-shrink rendering interfaces.
- It uses `partMap`, `RedstoneInteractions`, `IRedstonePart`, `NormalOcclusionTest`, `MicroOcclusion.recalcBounds`,
`onPartChanged`, `remPart`, and tile item drops.
**Migration consequence:** Java compatibility bases must retain the same trait defaults and generated composite
behavior. Test wireless interface dispatch through a composite tile, not just direct calls on the part.
### WitchingGadgets
WitchingGadgets registers multipart essentia tubes and buffers, with block converters and factories.
- Parts extend `McMetaPart`; the tube is slotted, and parts implement Thaumcraft transport/wand interfaces.
- Those external APIs are registered as pass-through interfaces, including the overload carrying client/server
generation flags.
- Connection logic walks `jPartList` and directly consumes other parts' normal and partial occlusion boxes.
- Rendering goes through `PartMetaAccess`; placement uses `canAddPart`/`addPart`.
**Migration consequence:** preserve flag-sensitive pass-through registration, Java occlusion iterables, slotted part
semantics, and `PartMetaAccess` behavior.
### MatterManipulator
MatterManipulator is the broadest external editor of multipart state.
- Analysis records each part's `getType`, calls `save` into NBT containing `id`, and captures `getDrops`.
- Application removes current parts with `remPart`, sorts microblocks before other parts, reconstructs through
`MultiPartRegistry.loadPart(type, nbt)`, calls `part.load(nbt)`, and adds through `TileMultipart.addPart`.
- It interprets core microblock type prefixes and NBT fields `material`, `shape`, `side`, `orient`, and `connMap`, and
transforms exact `PartMap` edge/corner numbering.
- Its mover detaches and reinserts the same tile object, rewrites coordinates, validates it, calls `onMoved`, then
performs dirty, render, block-update, lighting, and description-packet synchronization.
- Its apply path intentionally does **not** send a redundant description packet: rebuilding the tile a second time
previously produced null bounds. Packet timing and reconstruction side effects therefore matter.
**Migration consequence:** add capture/apply/move golden tests. This consumer will expose changes in part ordering,
factory semantics, core NBT, movement lifecycle, and over-eager network synchronization.
### GuideNH
GuideNH reconstructs and renders multipart tiles for guide scenes and exports part statistics. At `16f142417df1`,
the FMP integration uses direct calls guarded by mod-presence checks and Forge `@Optional.Method` annotations.
Commit `4a0cd02e` (2026-09-16, included in tags `1.3.33` onward) removed its FMP reflection and
`AccessorBlockMicroMaterial` mixin. The dependency is FMP `1.7.14`; this is not adoption of the unreleased Java API.
This upstream cleanup uses existing APIs and is not work performed by this migration project.
- Reconstruction still starts with `MultipartHelper.createTileFromNBT`, promotes client microblocks and tiles,
loads/binds parts, then calls `notifyTileChange` and `markRender`. Rendering calls `MultipartRenderer` directly.
- It directly invokes `MultipartGenerator$.MODULE$.generateCompositeTile` with a Scala iterable and
`MicroblockGenerator$.MODULE$.create`, then copies shape through `shape_$eq(byte)`.
- Preview paths retain `partList(): Seq`, Scala iteration/`ListBuffer`, and `loadParts(scala.collection.Iterable)`.
`Ae2ForgeMultipartBridge` also retains Scala part traversal. The old `partList_$eq` call is gone.
- Material export uses `jPartList`, `Microblock.material`, registry lookup and public `BlockMicroMaterial.block()` /
`meta()` getters. Statistics use `jPartList` and direct `getDrops`. Material lookup failures are logged and skipped;
getter failures propagate. See the [material guide](../api/MATERIAL_ACCESS.md) for differences from the example.
- `createPreviewTileFromNBT` and the Java generator/collection replacements have not been adopted.
**Migration consequence:** direct linking now enforces the retained companion/Scala contracts. All these calls have
counterparts in the port; no production API change is required. Material access already uses public getters, while
preview/Scala migration remains pending. Keep old private fields and setter descriptors for older supported jars
until pack adoption is verified; source tags alone do not establish installed-artifact compatibility.
### Schematica
Schematica's optional integration reconstructs multipart tiles from schematic NBT, especially on the client. It is
more invasive than its small binary footprint suggests.
- It reflects `MultiPartRegistry$.MODULE$` and the **private Scala-mangled field**
`codechicken$multipart$MultiPartRegistry$$typeMap`, casting it to `scala.collection.mutable.Map`.
- It resolves material IDs, obtains the registered microblock class from that map, and invokes
`MicroblockClass.create(boolean, int)`.
- It reflects part `load`, `onPartChanged`, `TileMultipart.loadParts`, `TileMultipart.createFromNBT`, and
`MultipartGenerator$.generateCompositeTile(TileEntity, scala.collection.Iterable, boolean)`.
- It parses tile NBT `parts`, each part's `id`, and microblock `material`; it rejects a preview if any part fails to
reconstruct.
**Migration consequence:** the registry's private field name **and Scala mutable-map representation are currently
effective public API**. A Java `Map` replacement will silently disable Schematica unless an exact compatibility field
is retained or Schematica is patched and deployed first. This is a higher-risk constraint than the constant-pool
inventory alone shows.
`MultiPartRegistry$` retains the exact private field as a Scala mutable-map wrapper backed by the canonical Java
`HashMap`. A regression test performs Schematica's lookup and verifies that both views resolve the same factory.
The port provides `MultiPartRegistry.getPartFactory(String)` as the supported replacement for map lookup.
It returns the exact registered factory or null without construction or missing-name logging. Schematica can reflect
this public static method and continue invoking `MicroblockClass.create(client, materialId)` on the returned object;
`loadPart` would incorrectly choose the server factory path for its client preview. The old private field remains.
See the [guide](../api/FACTORY_LOOKUP.md) and the now-available [Java tile generator](../api/COMPOSITE_GENERATION.md);
consumer patches and pack adoption remain pending.
### UtilitiesInExcess - future replacement, already a substantial consumer
UtilitiesInExcess is not in the `2.9.0-RC-2` JAR scan but is in scope because it is intended to replace Extra Utilities.
- `Content` implements `IPartFactory2` for `ue_fence`, `ue_wall`, and `ue_sphere`, with legacy Extra Utilities type
aliases when the old mod is absent.
- Parts extend `TMultiPart`, implement Java icon/normal-occlusion interfaces, call the normal occlusion protocol, and
render through microblock material helpers.
- Placement and connectivity use `canPlacePart`, `addPart`, `BlockMultipart`, neighboring `TileMultipart` instances,
`jPartList`, and part sub-boxes.
- Recipes and item enumeration consume `MicroMaterialRegistry.getIdMap()` as `scala.Tuple2[]` and use microblock
class IDs plus `ItemMicroPart.create`.
- Materials use name/ID lookup, packet material ID helpers, remapping, sounds, icons, drops, and rendering. Legacy
Extra Utilities material names are explicitly remapped for world conversion.
- At audited HEAD, the server factory reads NBT key `material` while `MaterialBasedPart.save` writes `mat`. That is a
UtilitiesInExcess-side inconsistency to resolve before relying on save/load round trips; FMP should not special-case
it.
**Migration consequence:** replacing Extra Utilities does not permit early removal of `IPartFactory2`, the Scala
`Tuple2[]` registry view, legacy material remapping, or the Java part/occlusion bridges. UtilitiesInExcess should be
added to compatibility CI before it enters the pack.
## Narrow consumers, still real contracts
| Consumer | Actual use | Compatibility requirement |
| --- | --- | --- |
| BloodArsenal | Registers decorative blocks/metas as `BlockMicroMaterial` instances | Constructor and `registerMaterial`; stable chosen names |
| Botania | Registers decorative blocks/metas as micro-materials | Same material registration API and block/meta behavior |
| Biomes O' Plenty | Registers historical BOP block/metas as micro-materials | Constructor, registry, and its dot-separated material names |
| Natura | Registers single/ranged block metas, using both `createAndRegister` and direct registration | Static helper plus registry API and generated material keys |
| TConstruct | Optional init plugin registers many smeltery/metal/glass blocks with `createAndRegister` | Helper availability and init-time registration behavior |
| Galacticraft | Reflectively constructs `BlockMicroMaterial` and chooses the first public method named `registerMaterial`; separately rejects `TileMultipart` as an energy receiver | Exact class/constructor names; compatible public registration method; tile class identity. Avoid incompatible same-name overloads because it does not check the signature |
| BloodMagic | Teleposer reconstructs multipart tiles with `MultipartHelper.createTileFromNBT` and sends a description packet after placement | NBT reconstruction, placement lifecycle, and `sendDescPacket` |
| Waila | Reflects `BlockMultipart`, reads tile NBT `parts`, then dispatches providers using each part tag's `id` | Block class name and tile/part NBT layout |
| AE2 Fluid Craft | Reflects `TileMultipart` and registers Waila part providers | Tile class name and `jPartList`/provider behavior reached by AE2 |
| GT5U | Detects `TileMultipart`, iterates `jPartList`, and finds a ProjectRed `GatePart` to expose its screwdriver slot. Since `5.09.54.205`, spray cans recolor ProjectRed insulated wires and bundled cables: retrace the block, take `(Integer) BlockMultipart.reduceMOP(hit)._1()` as a `jPartList` index, take the slot from `TSlottedPart.getSlotMask()`, then follow chained blocks through `partMap(slot)` and equal `getType()` | Tile identity, Java list view/order, part instance identity; exact `reduceMOP` static descriptor with Scala `Tuple2` return and boxed-index `_1`; ray-trace index agreeing with `jPartList` order; `partMap` slot numbering; stable type strings |
| ThaumicEnergistics | Loads `TileMultipart` with `Class.forName` and registers Waila body/NBT providers on it, so vis-link info still shows after a cover moves its AE2 parts into a multipart tile. Parts are found through AE2's `Platform.getPartFromTE`, not FMP. Added by `f6422d7` (2026-10-02, tags `1.7.62-GTNH` onward); no FMP compile dependency | Exact `codechicken.multipart.TileMultipart` class name; AE2 part-host pass-through on generated tiles |
| EnderCore | Tests items with `instanceof ItemSaw` for durability display | `ItemSaw` class identity and inheritance |
| IguanaTweaksTConstruct | Creates saws through `MicroblockProxy`, reads saw methods, accesses proxy companions, and reflectively mutates private `ItemSaw.harvestLevel` | Proxy methods and `MODULE$`, `Saw`/`ItemSaw` identity, exact `harvestLevel: int` field name/type until adoption; `setHarvestLevel(int)` is the supported replacement |
| Et Futurum Requiem | Reflectively gets and mutates static `int[] ButtonPart.metaSideMap` and `sideMetaMap` to add floor and ceiling orientation | Exact class and mutable static field names/types until migration; `ButtonPart.setOrientation` is the supported replacement |
## Source-only hazards
The constant-pool inventory identifies reflective class names, but source inspection adds exact member-level
requirements:
| Consumer | Hidden requirement | Likely symptom if broken |
| --- | --- | --- |
| Schematica | `MultiPartRegistry$.MODULE$`; field `codechicken$multipart$MultiPartRegistry$$typeMap` of Scala mutable-map shape; exact generator/load methods | FMP schematic tile reconstruction disables itself or returns no preview |
| Older GuideNH releases | Companion-only generator methods; `partList_$eq(Seq)`; `BlockMicroMaterial.block` and `.meta` mixin fields | Missing/incorrect guide preview, material export, or part statistics; current source instead links directly to companion/Scala methods |
| Et Futurum | Static mutable `ButtonPart.metaSideMap` and `sideMetaMap`, both `int[]`, until direct API adoption | FMP buttons attach with pre-fix orientation behavior |
| Iguana | Private `ItemSaw.harvestLevel` field until direct setter adoption | Existing saw cutting strengths are not adjusted |
| Galacticraft | Reflection by method name only for `registerMaterial` | Galacticraft micro-material registration is skipped after a caught exception |
| Waila | `BlockMultipart` string plus tile NBT `parts`/part `id` | No multipart HUD data |
These need targeted runtime tests or explicit downstream patches. They cannot be proven safe by `javap` ABI diffing.
`ConsumerReflectionCompatibilityTest` freezes the older GuideNH, Et Futurum, Iguana, and Galacticraft
member shapes above. `ButtonOrientationFunctionalTest` also freezes Et Futurum's exact array mutation and all-face
placement, then verifies the supported typed replacement. `ItemSawCharacterizationTest` runs Iguana's exact boxed
field mutation and the direct setter against shared storage. Schematica's registry lookup has its own live-view
regression test. The manual client checks remain necessary for end-to-end integration behavior.
## Data and ordering contracts
### Core NBT and identity
The following are read by code outside FMP and must be treated as serialized API:
- the tile's `parts` compound list;
- the `id` string in every part compound;
- built-in multipart type strings and registry lookup behavior;
- microblock `material`, `shape`, and orientation fields used by schematic/editor code;
- material names and remapping, including legacy Extra Utilities names;
- invalid/unknown part handling during `loadPart`, tile creation, and preview reconstruction.
Consumer-specific fields such as ProjectRed's `connMap` and UtilitiesInExcess's `mat` belong to their parts. FMP's
obligation is to invoke each part's hooks with the same tag and ordering, not to interpret or rewrite those fields.
### Observable part order
Part list order is not an internal detail:
- ProjectBlue identifies an edited part by its `jPartList` index;
- rendering code in ProjectRed and Extra Utilities indexes `partList` from hit data;
- MatterManipulator deliberately sorts placement, with microblocks first;
- GuideNH and Schematica build an ordered list before generating/loading a composite tile;
- Waila preserves tile NBT order when dispatching part providers.
The Java port may add faster indexed storage, but all published views, serialization, binding, ray-hit indices, and
packet consumers must observe one consistent order.
Current-branch verification: `MultipartHelperFunctionalTest` freezes ordered two-part NBT reconstruction and slot
rebinding plus the exact logical chunk-description framing and part payload. `TileMultipartLifecycleFunctionalTest`
freezes add/remove callbacks and the MatterManipulator-shaped live move, including ordered `onWorldSeparate` before
ordered `onMoved`/`onWorldJoin`, without replacing the generated tile.
### Material IDs and packets
Numeric material IDs are runtime registry identities used in descriptions and custom-part packets. Names are the
persistent identity. Preserve:
- deterministic name-to-ID lookup for one runtime;
- remap behavior for renamed materials;
- `writeMaterialID`/`readMaterialID` wire agreement;
- `materialName`/`materialID` round trips;
- the legacy `getIdMap(): scala.Tuple2[]` view until Extra Utilities and UtilitiesInExcess are migrated.
## Java API adoption ledger
This ledger tracks migration of a specific legacy contract, not completion of an entire consumer's migration.
Factory registration/lookup, material enumeration, tile collection/traversal access, tile loading/storage assignment,
client preview reconstruction, tile occlusion and box queries, render-ID accessors, named tile conversion results and
the struck-part index and inventory slot refresh are implemented on
`algent/java`. The [API index](../API.md) links the guides and compiling Java examples. These additions are not yet
tied to a released minimum dependency version. Unlisted contracts remain governed by the inventories above.
| Legacy contract | Consumer and inspected source | Supported replacement | Consumer migration/release | Target-pack adoption and removal gate |
| --- | --- | --- | --- | --- |
| `ButtonPart.sideMetaMap[side ^ 1]` live inverse lookup | ProjectRed `e173952e96a4` and separate preparatory migration checkout: `illumination/items.scala`, `ItemPartButtonCommons.newPart` | `ButtonPart.metaForSide(side ^ 1)`; [lookup contract](../api/BUTTON_ORIENTATIONS.md#reading-orientation-metadata) | FMP accessor/example and regression coverage added; consumer replacement requires a rebuilt FMP artifact; preparatory migration is not upstream adoption | Retain the array until ProjectRed and Et Futurum migrations are released/adopted and a fresh scan clears legacy use |
| `TRedstoneTile.openConnections(int)` | ProjectRed `e173952e96a4`: `transmission/redwires.scala` | Existing stable `IRedstoneTile.openConnections(int)` with the same mask/rotation logic; [guide](../api/TILE_TRAIT_ACCESS.md) | FMP source-access example and Forge coverage complete; consumer source patch/release pending | Retain the old runtime interface descriptor until adoption |
| `TSlottedTile.v_partMap()` array mutation | OpenComputers `2c00f79be24b`: `PrintPart.toggleState` | `TileMultipart.refreshPartSlots(part)`; [equality, cache and notification contract](../api/TILE_TRAIT_ACCESS.md#refreshing-a-changed-slot-mask) | FMP API/example complete; consumer source patch/release pending, preserving validation and following sound/notify/packet/schedule order | Keep the live array/accessor ABI until released pack adoption; do not replace it with reflection or a whole-tile reload |
| `TIInventoryTile.rebuildSlotMap()` raw trait call | AE2 `c690fbc273be`: `appeng/fmp/CableBusPart.notifyNeighbors` | `TileMultipart.refreshInventorySlots()`, a no-op without inventory parts, so the `instanceof` guard can go; [mapping and scope](../api/TILE_TRAIT_ACCESS.md#refreshing-inventory-slots) | FMP API, example and regression coverage complete; consumer source patch and release pending, keeping its neighbor notification afterward | Keep the `TIInventoryTile` interface and `rebuildSlotMap` until released pack adoption |
| External Scala `LightMicroblock` registered through `MicroblockGenerator.registerTrait` | ProjectRed `e173952e96a4`: `illumination/lightmicroblocks.scala` | Java source trait registered by name, `IGeneratedMaterial`, typed sibling traversal and halo helper; [example](../api/MICROBLOCK_EXTENSIONS.md) | FMP example tested; consumer rewrite/release, existing config/halo wiring and physical-client checks pending | Retain external Scala trait ingestion until released-consumer adoption and internal Scala-trait removal |
| `MultiPartRegistry$.registerParts(IPartFactory2, Seq)` and existing array calls | ProjectRed `e173952e96a4`: transmission, expansion and fabrication proxies | `MultiPartRegistry.registerPartFactory` with existing `IPartFactory2` methods and unchanged IDs | Source patch and release pending; Boolean-factory proxies separately need the two-method adapter described in the guide | No migrated pack version verified; retain all registration bridges and external trait support |
| `MultiPartRegistry$.registerParts(Function2, Seq)` | ForgeRelocationFMP `49a810b8c63b`: proxy init registering `rfmp_frame` | `IPartFactory2` creating a fresh `FramePart` on both paths, registered through `registerPartFactory` | Source patch and release pending; preserve `rfmp_frame` and keep converter/pass-through registration | No migrated pack version verified; retain the function companion descriptor |
| `MicroMaterialRegistry.getIdMap(): scala.Tuple2[]` | UtilitiesInExcess `3e107a1fe9bc15fcb6a808242ffda1354dac7c3a`: `FMPRecipeLoader.run`, `UEMultipartItem.getSubItems` | `materialCount()` with `materialName(int)` and, when needed, `getMaterial(int)` | Source patch and first released version pending; checkout used as reference only | No migrated pack version verified; retain the bridge |
| `MicroMaterialRegistry.getIdMap(): scala.Tuple2[]` | Extra Utilities 1.2.12, active supported consumer: NEI and microblock material enumeration | Same ID-based Java enumeration | Keep current compatibility; switching support to UtilitiesInExcess awaits approval and pack adoption | Verify Extra Utilities is absent and its replacement uses the new API before retiring this dependency |
| `TileMultipart.partList(): scala.collection.Seq` | ProjectRed `e173952e96a4`: illumination aggregation, packet indices and rendered-part lookup | `jPartList()` with unchanged indices, filters and aggregation | Source patch and release pending; Scala consumer code may remain Scala | No migrated pack version verified; retain the getter and external trait support |
| `TileMultipart.partList(): scala.collection.Seq` | OpenComputers `2c00f79be24b`: cable/print/network searches and aggregation | `jPartList()` with the same search/aggregation semantics | Source patch and release pending | No migrated pack version verified; retain the getter |
| `TileMultipart.partList(): scala.collection.Seq` | AE2 `fdedc3a8f023`: `FMPPlacementHelper.getPart` and `removePart` | Iterate `jPartList()`; retain last-match lookup and removal/break behavior | Source patch and release pending; September host-binding fix does not migrate traversal | No migrated pack version verified; retain the getter |
| `TileMultipart.partList(): scala.collection.Seq` | Extra Utilities 1.2.12: multipart renderer iterators | Iterate `jPartList()` without adding detached-part filtering | Retirement/replacement pending | Confirm absence or migration in the target pack before retiring the getter |
| `TileMultipart.partList(): scala.collection.Seq` and Scala loading | GuideNH `16f142417df1`: `Ae2ForgeMultipartBridge`, `ForgeMultipartHelpers` | `createPreviewTileFromNBT` for previews; `jPartList()` for remaining traversal | Direct calls replaced reflection in `4a0cd02e` (tags `1.3.33` onward); export/statistics use Java traversal, preview/AE2 paths still use Scala; setter call removed | Retain getter/loader for current source and setter for older supported jars; pack adoption unverified |
| `TileMultipart.loadParts(scala.collection.Iterable)` exact reflection | Schematica `3b03ee937953`: `nbt.ForgeMultipart` | `MultipartHelper.createPreviewTileFromNBT`; [complete preview contract](../api/CLIENT_PREVIEW.md) | Source patch and release pending; replace the whole reconstruction chain rather than one reflected method | No migrated pack version verified; retain the Scala loader descriptor |
| Private `MultiPartRegistry$` Scala `typeMap` field and `Map.get` / `Option` | Schematica `3b03ee937953`: `nbt.ForgeMultipart.init` and `createPart` | `MultipartHelper.createPreviewTileFromNBT`; factories opt in through `createPartForClientPreview` | Source patch/release pending; all-or-nothing lookup, client construction and loading are implemented | No migrated pack version verified; retain the exact private live Scala-map field |
| `MultipartGenerator$.generateCompositeTile(TileEntity, scala.collection.Iterable, boolean)` | Schematica `3b03ee937953` exact reflection; GuideNH `16f142417df1` direct companion call | `createPreviewTileFromNBT` for saved previews; static `MultipartGenerator.generateCompositeTile` for other staged reconstruction | Java API migration pending in both consumers; GuideNH removed reflection but still passes Scala parts | No migrated pack version verified; retain the companion and Scala descriptor |
| `MicroblockGenerator$.create(MicroblockClass, int, boolean)` and encoded shape copy | GuideNH `16f142417df1`: `promoteMicroblockToClient` directly calls companion and `shape_$eq(byte)` | `createPreviewTileFromNBT` for whole previews; static `MicroblockGenerator.create` and `setShape` for individual unbound parts | Reflection/private shape write removed in source; static Java/preview migration pending; validate client traits and shape callback ordering | No migrated pack version verified; retain companion singleton and exact descriptor |
| Private `BlockMicroMaterial.block` / `meta` accessor mixin and reflective material query | GuideNH `16f142417df1`: `resolvePrimaryMicroblockId`; mixin removed | Direct `jPartList()`, `Microblock.material()`, `getMaterial(int)`, `BlockMicroMaterial.block()` / `meta()`; [typed example and policy differences](../api/MATERIAL_ACCESS.md) | Upstream cleanup uses existing public getters since `4a0cd02e`, included in tags `1.3.33` onward; published artifacts, custom getter behavior and optional loading not validated here | No migrated pack version verified; retain private fields for older releases |
| Reflective mutation of `ButtonPart.metaSideMap` / `sideMetaMap` | Et Futurum Requiem `78a5744dfd33`: `compat.CompatMisc.runModHooksInit` | Two direct `ButtonPart.setOrientation(int, ForgeDirection)` calls; [mapping and lifecycle guide](../api/BUTTON_ORIENTATIONS.md) | FMP API/example complete; consumer source patch and first released version pending | Retain both public mutable arrays until the migrated release is in the target pack and a fresh scan confirms no legacy access |
| `MicroblockProxy$.MODULE$` saw access and reflective mutation of private `ItemSaw.harvestLevel` | IguanaTweaksTConstruct `2bc09889d3e2`: `ClientFMPProxy.updateSawRenderers`, `IguanaFMPCompat.postInit` | Use static `MicroblockProxy.sawStone()` / `sawIron()` / `sawDiamond()` / `useSawIcons()`; read `harvestLevel()` and call `setHarvestLevel(int)`; [state and lifecycle guide](../api/SAW_STRENGTH.md) | FMP Scala-free API example complete; consumer source/lifecycle patch and first released version pending | Retain the companion and private field until the migrated release is in the target pack; ensure Iguana runs before ForgeMicroblock post-init and rescan for legacy access |
| `NormalOcclusionTest$.apply(Traversable, Traversable)` | OpenComputers `2c00f79be24b`: `common.block.Cable.canConnectFromSideFMP`, `server.network.Network.canConnectFromSideFMP` | `NormalOcclusionTest.testBoxes(ownBounds.asJava, otherBounds)`; `otherBounds` already comes from Java `getOcclusionBoxes()` | Source patch and release pending; retain side/color/face filtering | No migrated pack version verified; retain the companion and descriptor |
| `NormalOcclusionTest$.apply(Traversable, Traversable)` | ForgeRelocationFMP `49a810b8c63b`: `FramePart.occlusionTest` | `NormalOcclusionTest.testBoxes(boxes.asJava, getOcclusionBoxes)`; retain combined normal/partial/collision boxes and caller order | Source patch and release pending; preserve temporary face bounds and replacement protocol | No migrated pack version verified; retain the companion and descriptor |
| `BlockMultipart.reduceMOP(MovingObjectPosition): scala.Tuple2` | GT5U `1a9469a13228`: `ColoredBlockContainer` ProjectRed wire branch, shipped in `5.09.54.205` | `BlockMultipart.hitPartIndex(hit)`, same index, `-1` when the hit carries none; [guide](../api/HIT_PART.md) | FMP API, example and regression coverage complete; consumer source patch and release pending, keeping its `ExtendedMOP` and coordinate guards | No migrated pack version verified; retain the exact static descriptor and boxed-`Integer` `_1()`; new in `2.9.0-RC-2` |
## Adoption constraints
The installed GTNH daily `2026-09-04+719` rescan scanned 241 jars, excluding FMP. Its 27 consumers retained
all 386 full member/type/reflection rows from `+678`: 35 inherited types, 255 members, 76 other types and 20
reflection strings. The `2.9.0-RC-2` rescan (240 jars, 28 consumers) keeps every `+678` member and type row and
adds 13 members and 4 other types. GuideNH `1.3.41` replaced 17 reflection strings with direct links, and
ThaumicEnergistics adds one. Source revisions above identify inspected checkouts, not guaranteed parity with newer jars.
GuideNH's upstream material-access cleanup ships in RC-2's `1.3.41`, but none of its pending Java API migrations do. No consumer has been verified to have completed the full Java API
migration; update artifact/adoption columns only with actual artifacts.
### Consumer-specific migration traps
- UtilitiesInExcess writes and loads its material name under `mat`, while `Content.createPart(String,
NBTTagCompound)` reads `material`. Fix the consumer factory before testing save/load or replacement adoption. FMP
must not add a fallback that hides the consumer's inconsistent persistent format.
- Galacticraft selects the first public `MicroMaterialRegistry.registerMaterial` method by name without checking its
parameters. Keep exactly one compatible public method with that name until Galacticraft migrates; the reflection
compatibility test pins this constraint.
- AE2's `FMPPlacementHelper.getPart` scans the whole part list and retains the last matching `CableBusPart`. Replacing
that loop with a first-match helper changes behavior. Iterate `jPartList()` and preserve the original selection and
removal rules.
- MatterManipulator and ForgeRelocationFMP both move the same live `TileMultipart`, but they own different validation,
render, lighting and packet policies. A future common move coordinator belongs in `MultipartHelper`, which already
owns cross-tile NBT and description-packet operations; `TileMultipart.onMoved()` remains the per-tile callback. Add
such a coordinator only when both consumers can express their existing synchronization policy through it.
- Waila, AE2 Fluid Craft and ThaumicEnergistics use `Class.forName` as an optional-mod loading boundary. That class lookup is intentional;
replacing it with a direct FMP type would make their otherwise optional integration load eagerly.
- GT5U `5.09.54.205` (in `2.9.0-RC-2`) is the first consumer to call `BlockMultipart.reduceMOP`. It needs only
the part index, which `hitPartIndex` returns as an `int`. Add a named result only if a second consumer needs the
rebased hit. Keep the `Tuple2` descriptor, and its boxed-`Integer` `_1()` that GT5U casts, until a migrated GT5U
release ships.
- FMP's own `ItemMicroPart` and `MicroRecipe$` still use legacy material arrays. Internal tuple paths also remain
in the generator and placement code, including `MicroblockPlacement.gtile()`. External adoption does not retire them.
- Existing `jPartList()` users need no rename. `forEachPart` filters detached/rebound parts and must not replace
arbitrary read/query loops. It delegates through the supported `operate(Function1)` override hook, which lifecycle
callbacks still use. See [traversal](../api/PART_TRAVERSAL.md).
- `setPartList` copies non-null list storage; the legacy setter retains the supplied sequence. Neither binds parts.
Use `loadPartList` for prepared reconstruction, preserving world/position setup and subsequent notifications.
See [loading and storage](../api/PART_LOADING.md).
- No direct supplied consumer call to the two-argument tile `occlusionTest` was found, but generated
`TPartialOcclusionTile` and placement/replacement dispatch still require it. `canAddPart`/`canReplacePart` callers
need no rename and must retain outgoing-part exclusion. Box-list queries are a separate contract;
[testOcclusion and testBoxes](../api/OCCLUSION.md) do not retire each other's bridges.
- `registerPartFactory` avoids Scala-dependent Java overload resolution. Preserve registration IDs, order,
ownership, partial-registration failure policy, and both NBT/packet construction paths. All legacy registration
entries remain; Schematica's private live Scala map is a separate dependency. See [registration](../api/PART_REGISTRATION.md).
- No supplied direct legacy render-ID or tuple-result conversion caller was found (GT5U's `reduceMOP` tuple is
covered above). Existing tile-only `getOrConvertTile` users
need no rename. New [render-ID](../api/RENDER_ID.md) accessors do not allocate/register a renderer;
[conversion results](../api/TILE_CONVERSION.md) still describe uninstalled placeholders.
- Saved client previews should use the complete [preview helper](../api/CLIENT_PREVIEW.md). The lower-level
[staged generator](../api/COMPOSITE_GENERATION.md) still does not copy/load/install parts automatically and remains
available for reconstruction flows that need candidate reuse or custom setup.
- GuideNH's [typed material getters](../api/MATERIAL_ACCESS.md) likewise honor overrides that raw mixin fields
bypassed. Preserve first-usable-part order, export filtering and failure behavior; validate custom overrides and
optional-mod loading. Physical-client construction and GPU previews remain release checks.
- Iguana must apply [saw strength](../api/SAW_STRENGTH.md) before ForgeMicroblock's post-init maximum calculation.
Et Futurum's [orientation setter](../api/BUTTON_ORIENTATIONS.md) maintains both inverse maps; keep the legacy
private field/public arrays until the respective released integrations are adopted.
## API boundary audit
Rechecked 2026-09-05 across 28 source checkouts, active Extra Utilities compatibility and the installed `+719`
constant-pool inventory. No external calls were found to the 15 tile/material-registry implementation hooks listed
in the [API boundary table](../API.md#supported-api-and-internal-hooks). Searches covered FMP-importing Java/Scala,
method names and reflective strings; historical GuideNH comments avoiding `from`/`copyFrom` and WR-CBE's unrelated
`RenderWireless.loadIcons` were excluded. This is evidence about the audited references, not every possible mod.
Supported exceptions are OpenComputers `2c00f79be24b`, `PrintPart.scala:171`, clearing slots before
`tile.bindPart(this)`, and ProjectRed `e173952e96a4`, `gatepartrs.scala:74`, calling `internalPartChange(this)`
between packet/dirty work and selective neighbor notification. Cache binding neither places nor rebinds a part
and is not universally idempotent. Local part notification does not perform world updates. Internal markers change
no descriptor and authorize no removal; `operate`, `getOrConvertTile2` and material `loadIcons` retain their
separate legacy/extension contracts.
## Extension and converter migration
- The [illuminated Java microblock example](../api/MICROBLOCK_EXTENSIONS.md) uses name-based registration and
`IGeneratedMaterial`. Register before input-class loading; keep inherited access in an ordinary helper with
`Object` parameters and dispatch through the stable base. It preserves metadata 16–31, cutter metadata modulo
16, all-shape selection, strict sibling filtering, light rounding/capping, pass-zero halos and hollow trimmed strips,
without new part NBT/packet fields. Headless client-body probes do not replace physical-client construction,
configuration/halo integration and released ProjectRed adoption.
- Existing `IPartConverter`/`registerConverter` users need no replacement API; companion users can use the static
entry. Preserve separate factories, IDs, Chisel metadata selection, ForgeRelocationFMP frame construction,
OpenComputers original-tile lookup, AE2 state copying and consumer-specific cleanup. The
[converter guide](../api/BLOCK_CONVERTERS.md) covers lifecycle; actual inventory/network transfers need integration checks.
- Raw trait classes become interfaces at runtime. ProjectRed should query `IRedstoneTile.openConnections` while
preserving rotation/masks; OpenComputers should use `refreshPartSlots` while preserving validation and subsequent
sound/notify/packet/schedule order; AE2 should call `refreshInventorySlots` before its neighbor notification. Keep their legacy runtime interfaces until adoption. See
[stable tile access](../api/TILE_TRAIT_ACCESS.md).
- The [custom tile-trait guide](../api/CUSTOM_TILE_TRAITS.md) covers a top-level Java input, separate marker/capability
interfaces and ordinary helpers. Stateful extensions still own copy, persistence, synchronization and lifecycle
behavior. No direct custom multipart tile-trait registration was found in supplied consumer source; built-in traits,
pass-through interfaces and ProjectRed's microblock registration are distinct paths. Example coverage does not
authorize retirement of any existing consumer contract.
+224
View File
@@ -0,0 +1,224 @@
# Java migration divergences
Current intentional differences from the `1.7.12` Scala reference. Upstream `master` fixes merged since then
(through `1.8.0`) are ported; rows naming an upstream PR record whether the Java fix matches it.
This is a compatibility ledger, not a port diary.
An unchanged implementation needs no entry. Track remaining work in [migration status](README.md), client gaps in
[manual release checks](MANUAL_CHECKS.md), and use the [performance protocol](MAINTAINERS.md#performance-validation)
for measurements. Superseded decisions and per-port narratives remain in git history.
“No audited consumer” means the frozen GTNH binary inventory and consumer-source audit, not every possible
third-party mod. Removed members can still break unaudited consumers. Check
`docs/migration/COMPATIBILITY.md`, which holds both the binary inventory and the consumer-source
audit, before extending this list.
## Runtime and error behavior
The multipart block intentionally retains the pre-PR #54 unlocalized name `tile.multipart`.
PR #54 (`2d050bd`) renamed it to `tile.codechicken/multipart`; `cb3bef7` reverted that part to preserve
the established name. The block registry ID remains `ForgeMultipart:block`. This is an intentional rollback
of the later upstream rename, not a divergence from the `1.7.12` reference.
| Area | Difference and consequence |
| --- | --- |
| Raw microblock recipe material lookup | Skips `MissingMicroMaterial`, whose recovery item is stone, so sawing stone selects the real stone material. Existing missing-material microblocks retain their recovery behavior. This fixes a pre-existing Scala bug, also fixed upstream in PR #61. |
| `BlockMicroMaterial.icont()` after a texture stitch | `loadIcons` still builds icons eagerly, then marks them stale; the first `icont()` read after the stitch re-reads the block's icons once. Icons that another mod finishes in a later `TextureStitchEvent.Post` handler (Chisel's CTMLib `-v4` submaps) are picked up instead of rendering as missing or previous-stitch textures. Icons assigned through `icont_$eq` are kept. Upstream PR #63 targets the same bug by lowering the stitch handler to `EventPriority.LOW`; this port does not need that ordering. |
| Client part additions | Reuses an existing multipart tile or creates one without converting the stale client block. Conversion and its outgoing packets remain server-side, avoiding duplicate parts and client disconnects. Matches upstream PR #62. |
| `BlockMicroMaterial.createAndRegister(Block, Seq, String)` | Registers every supplied metadata value instead of only zero, including dark-oak logs and leaves and their legacy-name remaps. This fixes a pre-existing Scala bug; material IDs are rebuilt through the existing registry mapping. |
| Chunk scheduled-tick restoration | Reactivates chunks with restored scheduled ticks so their callbacks resume at the saved deadlines. The Scala implementation restored entries without activating their chunk. NBT layout and duplicate-scheduling behavior are unchanged. |
| Scheduled ticks of moved tiles | `TileMultipart.onMoved` hands its parts' pending scheduled and random ticks to the chunk that now contains the tile, keeping their deadlines; moves requested from a tick callback apply after that tick's processing. The Scala implementation left them in the source chunk, so they were lost if it unloaded first, and were saved at the wrong position. Same-world moves only. This fixes a pre-existing Scala bug. |
| World scheduler clock loading | Retains successfully loaded `schedTime` instead of overwriting it with total world time. Missing or unreadable files still fall back to world time. This fixes a pre-existing Scala bug and preserves the clock used by saved absolute tick deadlines; the file format is unchanged. |
| Converted tile loading | Copies the source tile coordinates to a replacement produced by `MultipartSaveLoad.loadTiles` before assigning its world and validating it. The Scala implementation left converted replacements at their default coordinates. |
| Placement-modifier player lifecycle | Removes cached control-key state when a player logs out and transfers it from the old player object to its replacement on clone. The Scala implementation retained entries until server shutdown. |
| `IDWriter` before `setMax` | `read`/`write` throw `IllegalStateException` instead of `NullPointerException`. Uninitialized use is unsupported. |
| `PacketScheduler` invalid `maskWidth` | Throws `IllegalArgumentException` instead of `scala.MatchError`. Valid widths remain 1, 2, 4 and 8. |
| `NormalOcclusionTest.apply(Traversable, Traversable)` | Materializes both inputs into Java lists before testing instead of nested Scala `forall`. Finite, side-effect-free collections give the same result; eager traversal can change side effects, failure timing and termination for unusual inputs. |
| `MultipartRenderer` dynamic-part guard | Uses short-circuit `\|\|` instead of `\|`; the second getter is no longer evaluated when the first operand succeeds. Ordinary getters give the same render decision. |
| `ControlKeyModifer.map()` | The exposed Java map has no Scala default-value wrapper: an absent key returns null from `get`, not false from Scala `apply`. Use `isControlDown` for the unchanged absent-means-false behavior. |
| Public companion constructors, including `ASMImplicits.ExtBitSet$` / `ExtClass$` | Explicit construction creates an independent instance instead of replacing `MODULE$`. Java initializes the retained final module field in its static initializer; use `MODULE$` for singleton identity. |
| `registerJavaTrait` abstract inputs | Abstract Java classes are accepted instead of throwing `IllegalArgumentException`. Declared abstract methods become generated-interface contracts without helper bodies; a later mixin must implement them before those members can be invoked. A no-argument abstract-mixin constructor may call an argument-taking superclass constructor; registration discards that direct call and its argument evaluation because the composite invokes the real base constructor first. This enables Java microblock mixins without changing existing concrete registrations. |
| `registerJavaTrait` members annotated `@SideOnly` | The old Java path ignored the annotation. It now omits opposite-side fields and methods from generated metadata and output, matching Forge and the Scala-trait path; visible and invisible annotation tables are both accepted. If the no-argument constructor is absent, including after Forge has already stripped it, an empty `$init$` preserves the generated initializer contract without running its body. Current-side members are unchanged. No audited Java registration relied on the old retention. |
Concrete collection implementations also change without changing the declared `java.lang.Iterable`/`List` contracts:
| Return path | Reference → Java |
| --- | --- |
| `JCuboidPart.getSubParts` / `getCollisionBoxes` | Scala `Seq` adapter → immutable `Collections.singletonList` |
| `MultipartHelper.IPartTileConverter.convertMulti` default | Scala `Seq` adapter → `Collections.emptyList` / `singletonList` |
| `Microblock.getDrops` | Java view of Scala `ListBuffer` → mutable `ArrayList` |
Code depending on concrete collection classes or their exact mutation failure behavior must adapt.
## Removed or changed binary surface
These removals were accepted because neither audit identified a consumer of the removed surface. This does not
authorize removing other members of the same type.
| Area | Removed or changed surface |
| --- | --- |
| `IDWriter` | Removed `write()`, `write_$eq(Function2)`, `read()` and `read_$eq(Function1)`. Use the Java methods listed below. |
| Both registries | `MicroMaterialRegistry.readIDMap` and `MultiPartRegistry$.readIDMap` return `java.util.List<String>` instead of `scala.collection.Seq<String>`; the return descriptor changes. |
| Registry compiler accessors | Removed `MicroMaterialRegistry`'s public mangled `$$idMap()`, `$$typeMap()` and `$$nameMap()` accessors, and the five `codechicken$multipart$MultiPartRegistry$$...()` accessors. Schematica's separate private `MultiPartRegistry$.$$typeMap` **field is retained** as a live Scala-map view; it is not one of the removed methods. |
| `NormallyOccludedPart` | Removed the inferred `getType(): scala.runtime.Null$` overload; the `String` method remains. |
| `MissingMicroMaterial` | Removed static `canRenderInPass(int)` and `isSolid()` forwarders. The companion no longer declares these methods but inherits the interface defaults. |
| `TileMultipart` | Removed compiler accessor `protected$worldObj(TileMultipart)`. |
| `BlockMultipart` | Removed `hasTileEntity$default$1()`; source callers must supply metadata explicitly. |
| `TileCache` | `map()` now returns Java `Map`; `add`/`remove` return `void` instead of Scala `Option`; `apply(BlockCoord)` returns a nullable `FlaggedTile` instead of `Option`. |
| `TileCache.FlaggedTile` | Dropped Scala case-class `copy`, copy-default getters, `canEqual`, value `equals`/`hashCode`/`toString`, product methods, and `scala.Product`/`scala.Serializable`. It now has ordinary object identity semantics; `t()` and `removed()` remain. |
| `ControlKeyModifer` | Replaced `isClientPressing_$eq(boolean)` with `setClientPressing(boolean)`; `map()` returns Java `Map<EntityPlayer, Boolean>` instead of Scala mutable `Map`; removed `playerControlValue(EntityPlayer)` and its implicit wrapper type. |
| `ControlKeyHandler` | Former static facade is now a `KeyBinding` subclass with `INSTANCE`. `wasPressed`/`tick` are instance methods, and the twelve inherited-KeyBinding static forwarders disappear. Initializing this client-only class now initializes its binding. |
| `MultipartRenderer` | Removed inherited-TESR static forwarders `func_147498_b`, `func_147496_a` and `func_147497_a`. |
Removed named helpers and companions (besides private compiler artifacts covered below):
- `JPartialOcclusion$class`, including `allowCompleteOcclusion` and `$init$`.
- `MicroMaterialRegistry$IMicroMaterial$class` and its four statics.
- `TRandomUpdateTick$class`, including `onWorldJoin` and `$init$`.
- `TScheduledPacketPart$class` and `PacketScheduler$`.
- `IconHitEffects$`.
- `TileCache$` and `TileCache$FlaggedTile$`.
- `ControlKeyModifer$`, `ControlKeyModifer$ControlKeyValue` and `ControlKeyHandler$`.
- `codechicken.multipart.package` / `package$` and `codechicken.microblock.package` / `package$`.
Their logger aliases are replaced by the corresponding proxy's `logger()`.
Generated-tile helpers removed only from the **raw artifact** are listed separately below; Forge recreates them.
Other retained `$class` bridges and `MODULE$` companions are not covered by this removal decision.
## Additions and default-method changes
| Area | Additive Java entry points |
| --- | --- |
| `IDWriter` | `write(MCDataOutput, int)` and `read(MCDataInput)` |
| `JCuboidPart` | Static `subParts`, `collisionBoxes` and `renderBreaking` implementations for explicit forwarding |
| `JItemMultiPart` | Static `hitDepth` and `onItemUse(part, ...)` implementations |
| `MicroMaterialRegistry` | Static `setupIDMap`, `calcMaxCuttingStrength` and `loadIcons` forwarders |
| `PacketScheduler` / `TScheduledPacketPart` | Static `sendScheduled()` on the facade and `readMask(part, packet)` on the interface |
| `TileMultipart` | `hasDynamicParts` (false by default), `renderStatic`, `renderDynamic` and `randomDisplayTick` hooks for dispatching generated overrides through a stable superclass |
| `MultipartMixinFactory` | Four additional static forwarders: `onCompiled`, `autoCompleteJavaTrait` and the two mangled `ASMMixinFactory` parent helpers. Scala emitted them when the base became Java with its original public JVM access; the Java facade retains them. Existing facade entries are unchanged. |
| `MultipartEventHandler` / `MultipartEventHandler$` | Public `playerLoggedOut(PlayerLoggedOutEvent)` and `playerCloned(PlayerEvent.Clone)` event handlers for placement-modifier state cleanup and transfer |
| `MultipartHelper` | `createPreviewTileFromNBT(World, NBTTagCompound)` builds an uninstalled client composite directly from saved multipart NBT and rejects unsupported parts as a whole |
Previously abstract JVM interface methods now have Java defaults, allowing inheritance without Scala forwarders:
| Interface | Default methods |
| --- | --- |
| `JPartialOcclusion` | `allowCompleteOcclusion` |
| `TFacePart` | `solid`, `redstoneConductionMap` |
| `JIconHitEffects` | `getBreakingIcon` |
| `TItemMultiPart` | `getHitDepth` |
| `TEdgePart` | `conductsRedstone` |
| `Saw` | `getMaxCuttingStrength` |
| `MicroMaterialRegistry.IMicroMaterial` | `loadIcons`, `canRenderInPass`, `isSolid` |
| `TScheduledPacketPart` | `writeScheduled`, `readScheduled` |
| `PlacementGrid` | `render`, `drawLines`, `glTransformFace` |
| `MultiPartRegistry.IPartFactory2` | `createPartForClientPreview`; defaults to unsupported, while legacy Boolean/function adapters and built-in microblock factories construct their client variant |
`ItemSaw` consequently no longer declares `getMaxCuttingStrength`; ordinary calls still resolve to the default,
but declared-member reflection differs. The same distinction applies to the two `MissingMicroMaterial$` methods above.
The `TNormalOcclusion` super accessor
`codechicken$multipart$TNormalOcclusion$$super$occlusionTest(TMultiPart)` additionally loses `ACC_SYNTHETIC` and
becomes a default returning true, so javac can see and implement it. `NormallyOccludedPart` inherits it rather than
declaring its own. Existing Scala binaries retain their explicit super-chain overrides.
## Recompiling Scala consumers
Binary descriptors alone do not preserve Scala source semantics after `ScalaSignature` metadata is removed.
### Trait composition
A Java interface cannot supply a Scala trait's class supertype or its linearization. A superclass method wins over
an interface default, so recompiling `extends TMultiPart with TCuboidPart` silently selects the empty superclass
methods. Explicit forwarding is required where the implementation remains abstract:
| Trait | Source migration |
| --- | --- |
| `TCuboidPart` | Extend `JCuboidPart`, or forward subparts, collision boxes and breaking rendering to its statics. |
| `TNormalOcclusion` | Explicitly combine `NormalOcclusionTest.apply(this, other)` with the intended super chain. Audit existing `super.occlusionTest` calls too: they no longer route through the old trait. |
| `TIconHitEffects` | Explicitly forward `addHitEffects` and `addDestroyEffects` to `IconHitEffects`. |
| `TItemMultiPart` | Explicitly forward `onItemUse` to `JItemMultiPart`; the inherited Item method otherwise wins. |
| `TRandomUpdateTick` | Explicitly implement `onWorldJoin` with `TickScheduler.loadRandomTick(this)`. |
| `TScheduledPacketPart` | Explicitly forward `read` to `TScheduledPacketPart.readMask(this, packet)`. |
| `ScratchBitSet` | Implement both methods and storage accessors, and initialize storage explicitly; the retained `$class` helper supplies the original implementations. |
Previously compiled calls to **retained** `$class` bridges still link. This does not apply to the removed helpers above.
### Source syntax and generic signatures
- An object used as a value now needs `X$.MODULE$` where that companion is retained (event handlers, proxies,
recipes, packet handlers, materials and generators). Static calls alone do not supply a singleton value.
- Object-application sugar becomes explicit `.apply(...)`, e.g. `NormalOcclusionTest.apply(...)` and
`MicroblockPlacement$.MODULE$.apply(...)`.
- `ASMImplicits` no longer provides Scala implicit/value-class syntax. Use `nodeName(clazz.getName)` and
`ExtBitSet$.MODULE$.copy$extension(bits)` explicitly, or construct its retained Java wrappers. Existing boxed and
`$extension` binary entry points remain; implicit conversion requires Scala metadata Java cannot emit.
- Scala property assignment needs the explicit Java-authored `_$eq(...)` method, e.g. `renderID`, `loadingWorld`,
`angelicaCompat` and microblock `shape`.
- `ByteCodeReader.advance(length)(value)` becomes `advance(length, value)` when recompiling Scala. Argument
evaluation remains eager, and previously compiled calls retain the same binary descriptor.
- `ASMMixinFactory` constructor parameters and `construct` arguments need an explicit Scala `Seq`, not Scala
varargs syntax. Overrides of `onCompiled` and `autoCompleteJavaTrait` must be public: Java preserves their original
public JVM access without Scala's protected-source metadata.
- `tile.partList(i)` becomes `tile.partList.apply(i)`. Static bounds getters on Face, Corner, Edge and Post factories
need `aBounds()(index)` instead of `aBounds(index)`; Java no-argument methods may need explicit parentheses.
- `TileMultipart.getOrConvertTile2` exposes `Tuple2<TileMultipart, Object>` instead of a Scala-typed Boolean second
element; source callers need a cast. Scala 2.11 callbacks to `operate(Function1<..., BoxedUnit>)` need an explicit
`AbstractFunction1` instead of the previous Unit-returning lambda adaptation.
- The Face, Corner, Edge, Post and Hollow factory **companions** widen `baseTrait` to
`Class<? extends Microblock>` from their specific trait type. Their static facades retain the specific generic
type, and the raw JVM return descriptor remains `Class`.
- `MultiPartRegistry.registerParts(IPartFactory, String[])` and the `IPartFactory2` array overload gain Java varargs
flags. `BlockMultipart.addCollisionBoxesToList` uses raw `List` rather than `List<?>` to override vanilla. Neither
changes its raw JVM descriptor.
## Generated tile traits: raw artifact versus Forge runtime
These ports replace Scala interfaces/helpers with concrete Java mixin inputs. Forge rewrites the inputs back into
interfaces and generates implementation helpers. Existing binaries retain the runtime interface calls, but code
recompiled against the **untransformed dev jar** may emit `invokevirtual` or `getfield` against a type that becomes
an interface, causing verification/linkage failures. A transformed compile stub or explicit source guidance is
required before claiming source-compatible downstream rebuilds.
| Raw artifact change | Affected types |
| --- | --- |
| Interface + `$class` → concrete `TileMultipart` subclass | `TSlottedTile`, `TRedstoneTile`, `TTileChangeTile`, `TFluidHandlerTile`, `TileMultipartClient` |
| Interface + `$class` → concrete child mixin input | `TRandomDisplayTickTile` (extends the registered `TileMultipartClient` input) |
| Removed raw `TIInventoryTile$class`; moved implementation into `JInventoryTile` input | `TIInventoryTile` itself remains a Java interface. Source consumers should target it, not the transformed `JInventoryTile` class. |
Inherited/foreign-field and callback workarounds add package-private access shims for redstone, tile-change,
fluid, inventory and both client traits; they are not new consumer APIs. Transformer constraints and shim recipes
are documented in the [maintainer guide](MAINTAINERS.md#trait-and-dispatch-rules).
The client-trait port also deliberately extends the Java-trait transformer:
- Registered Java traits may extend an already registered Java trait; the parent runtime interface participates in
hierarchy and linearization. A child's `super` call dispatches to the parent trait's implementation, or to the
base class when the parent trait does not override that method.
- Explicit field accessors are recognized rather than duplicated.
- Transient input fields are excluded from automatic `copyFrom`. Client render caches use this opt-out; their
generated runtime fields remain ordinary private fields.
## Shared classfile differences
These are accepted once for the migration, not repeated for every otherwise equivalent port:
- Java-authored types lose Scala signature/marker attributes and use Java source-file/debug metadata. Static facades
and helper classes gain private constructors where Scala emitted none. Java class initializers lack Scala's
`ACC_PUBLIC`, and singleton publication follows Java initialization rather than Scala's constructor assignment.
- Unreferenced Scala `$$anonfun$`/anonymous implementation classes and private compiler accessors disappear or are
replaced by Java helpers/lambdas. Their names are not supported API. This does **not** include named compatibility
bridges or reflective fields: audit those individually. Retained Scala traits still emit their required helpers.
- The `Object[]` renderer bridges on `ItemMicroPartRenderer$` and `ItemSawRenderer$` are ordinary Java methods rather
than synthetic Scala methods; signatures and dispatch remain available.
- The private scratch `ThreadLocal` fields on `MicroblockGenerator$` and `MultipartGenerator$` lose `ACC_FINAL` so
their public Scala-trait setters can still replace storage.
- The private `ItemSaw.harvestLevel` field loses `ACC_FINAL` so `setHarvestLevel(int)` can update the same storage as
the retained getter and old Iguana reflection. Its name, type and visibility remain unchanged.
- TickScheduler's private Scala scheduler types become package-private static nested Java classes, retaining their
binary names.
## Updating this ledger
Add only a new effective runtime, binary, source or classfile difference, with its consequence and reason for
acceptance. Amend an existing row when a later change supersedes it. Do not add passing test counts, unchanged
behavior, build observations, performance claims or a “no divergence” section for each new port.
+149
View File
@@ -0,0 +1,149 @@
# ForgeMultipart maintainer constraints
These constraints explain the retained build and runtime machinery. Consumer migration belongs in the
[adoption ledger](COMPATIBILITY.md#java-api-adoption-ledger); remaining release checks belong in
[MANUAL_CHECKS.md](MANUAL_CHECKS.md). Keep this guide about current mechanisms, not completed-port history.
## Build and runtime boundaries
- Preserve a Java 8 artifact with equivalent startup, gameplay, serialization and network behavior. The target
modern-runtime policy spans Java 17–26; validate packaged releases on the selected supported runtime. Equal
throughput across Java versions is not required. The deobfuscated Forge test runner uses Java 8; the current
modern dedicated-server run tasks are not a substitute for packaged validation.
- Keep `enableModernJavaSyntax = false` while Scala 2.11.5 remains. Normal Java and joint Scala/Java compilation
use Java 8. Helpers importing retained Scala models belong in the joint `src/main/scala` source set because
`compileJava` runs before those Scala types exist.
- `scalaCompileOptions.force = true` prevents stale `Tags.VERSION` constants in joint-compiled Java `@Mod`
annotations. Zinc otherwise misses those consumers when the generated constant changes. Verify all five mod
annotations in dev/release artifacts against their artifact version; replace the guard only with equivalent coverage.
- Keep registered trait inputs and compatibility facades conservative. Moving `RedstoneInteractions$` or
`BlockMultipart` pulls transformer-sensitive dependencies; `RenderPartResolver` is needed by joint compilation
before Java helpers that use it. The explicit `Microblock` cast in `PostMicroblockTraitLogic` is required by the
retained Scala declaration.
- GTNHLib is compile-only here. Its fastutil compile classpath does not grant a runtime dependency. Declare that
dependency explicitly before using fastutil in ordinary code; require profiling evidence for such a change.
## Retained compiler constraints
- Scala multiple-trait inheritance still needs metadata. Java registration incorporates an already registered
superclass trait, not implemented Scala interfaces. `CommonMicroblockClient` combines three parents, including
`TMicroOcclusionClient`. Preserve state/accessor/super bridges until a characterized replacement exists.
- ProjectRed's external `LightMicroblock` requires ScalaSignature ingestion, `$class` helpers and generated
dispatch until its replacement is released and adopted. Abstract Java mixins and side filtering do not remove
that requirement, nor FMP's internal Scala trait inputs.
- ScalaSignature primitive literal `value()` methods coexist with erased `Object value()` bridges that Java
source cannot declare together. Five generic inner-construction branches require exact outer-instance bindings.
Preserve inferred Scala return types too: an explicit type can alter ScalaSignature without changing a JVM descriptor.
- Javac interprets nested `ClassInfo$` names and `IterableLike.view()` differently from scalac. Keep construction
callbacks, the initial Scala `.view`, lazy builders and virtual dispatch; avoid path-dependent symbols or generated
companion classes in Java-callable signatures. Joint helpers resolve `ASMMixinCompiler$.MODULE$` internally.
- Scala 2.11.5 rejects a Java class beside its same-name Scala object. Port `StackAnalyser`'s class, companion,
model and serialization contracts together, rather than splitting their public shapes mechanically.
- Preserve characterized algorithm quirks during mechanical conversion: primitive `NEWARRAY` throws
`MatchError: 188`, wide arguments can misindex `getSuper`, and Scala `String` aliases decode as
`Lscala/Predef/String;`. Successful external fixtures use `java.lang.String`; fix these separately with regressions.
- Metadata keys distinguish dotted/slashed names; byte-cache publication normalizes and invalidates only that key.
Parse failures retain bytes, null results are cached, load failures retry, and dump failures follow publication.
Ordinary duplicate `define` errors remain reflection-wrapped; direct LinkageError handling is case-sensitive and
its null-message behavior is characterized. Do not silently alter these during extraction.
## Trait and dispatch rules
- A superclass method wins over a Java interface default, silently bypassing former Scala trait behavior. Audit
implementors and existing `super` call sites; `PostMicroblock.occlusionTest` is a concrete example. Recompiled
implementors may also lose Scala-generated forwarders when a trait gains a default.
- A Scala trait extending a class is only an interface in bytecode. Synthetic super accessors are invisible to
javac. Preserve required non-synthetic bridges; retained Scala super calls can stay in Scala using the existing
result-code pattern instead of eager callbacks. `TScheduledPacketPart.readMask` is the static-helper pattern for
a trait method shadowed by a superclass.
- `private[multipart]` reaches sibling packages, so Java package-private is not equivalent. Keep required public
descriptors and companion-only methods. Check reflective string names as well as bytecode references before
removing companions; `MultipartHelper$` is a reflective dependency.
- Common Java must not use a side-stripped static facade. `MultipartProxy$.MODULE$.postInit()` retains virtual
server fallback; the corresponding static forwarder is stripped on dedicated servers.
- Registered Java trait classes become interfaces at runtime. Consumer calls must use stable base/capability
types, not raw class/field opcodes. See [tile access](../api/TILE_TRAIT_ACCESS.md) and
[custom trait authoring](../api/CUSTOM_TILE_TRAITS.md).
- Put inherited calls, inherited field access, argument-owned field access and primitive-array allocation in an
ordinary helper outside the trait transformer. Use `Object` parameters when a trait-to-base cast must survive
javac; a raw subclass parameter can cause javac to omit the required cast.
- Trait inputs cannot carry an `InnerClasses` attribute; anonymous classes, lambdas and string switches need
transformer-specific scrutiny. Keep callbacks in named helper classes. Register parent Java traits first.
Mark runtime-only fields `transient` when generated `copyFrom` must not copy them.
- Abstract mixin methods remain interface contracts until implemented by a later mixin. Source constructors must
be no-argument; registration removes the superclass call and its argument evaluation but retains field initialization.
- Java API examples must compile against the packaged dev jar with Scala excluded. Merely removing imports does
not prove this: overloaded `loadParts`/`registerParts` still required Scala during resolution, motivating distinct
`loadPartList`/`registerPartFactory` names. Preserve legacy override dispatch underneath the Java adapters.
## Verification
For a source conversion, characterize the untouched implementation first and preserve the compiled reference
consumers. Compare names and descriptors together, modifiers, generic signatures, reflective private fields,
class inventory, serialized models, packets/NBT and generated interfaces. Keep behavior fixes separate from
mechanical ports. Coverage percentages and signature counts alone are insufficient.
```powershell
.\gradlew.bat spotlessApply checkstyleTest build
.\gradlew.bat runFunctionalTestServer
.\gradlew.bat --stop
.\gradlew.bat clean spotlessApply checkstyleTest build
.\gradlew.bat runFunctionalTestServer
```
A Scala-to-Java replacement needs clean verification: Zinc can retain the removed Scala class and package it
instead of exercising the new source. Stop the daemon if Windows holds build outputs open. Verify packaged
class version 52 and mod-version freshness, including after the release commit.
JUnit reports are under `build/test-results/test/` and `run/server/junit-out/`; inspect counts, failures, errors and
skips. The Forge task rejects missing/failed reports. Keep that CI gate required. Generated dumps are under
`run/server/asm/multipart/`; assert a nonzero expected inventory and investigate differences before normalizing
proven debug/private-name changes. Headless client-body probes do not validate actual client loading or GPU output.
Use Forge for world/registry initialization and FakePlayer cases. Error-path logging needs initialized registries;
shared global state must be restored between tests. Headless class-initialization failures can differ between the
first and subsequent calls, so probes use `LinkageError` rather than one exact subclass. Archived test mods lacking
current registered content need disposable worlds to avoid missing-mapping prompts; restore server configuration.
Run `java tools/AbiScan.java "<instance>/.minecraft/mods" ForgeMultipart` on JDK 17+ and compare full rows with
`src/test/fixtures/abi/gtnh-2.9.0-rc2-consumers.txt` (and `gtnh-daily-678-consumers.txt` for row history).
Then check that every scanned type and member still resolves against the compiled port: a static resolver flags
runtime-generated `scalatraits` accessors such as `TSlottedTile.v_partMap()`, which the Forge smoke test covers
instead. Preserve audited source revisions separately from pack versions.
Compile frozen Scala fixtures with Scala 2.11.5 on Java 8 against the reference artifact using
`scala.tools.nsc.Main -target:jvm-1.8`, not against the replacement. Store bytes under `src/test/resources/compat/`
and provenance/hashes in `src/test/fixtures/README.md`.
## Performance validation
Profile typical, busy and explicitly labeled stress scenes: mixed ticking/redstone tiles, placement/occlusion,
chunk transitions and previews, frame moves, client microblocks/halos, multiplayer packets, startup and first-use
class generation. Historical focused results do not establish current whole-pack gains.
Record world/snapshot, pack and consumer/FMP revisions, hardware, JVM/flags/heap, graphics/view distance, part/trait
counts and repeatable actions. Restore equivalent state. Compare baseline versus changed FMP with consumers fixed,
then old versus migrated consumer calls on the same FMP artifact; include a compatible Scala reference if possible.
Keep runtime/configuration fixed and separate cold startup from warmed play, CPU-bound from GPU-bound scenes.
Start with five independent runs per variant, alternate order, match warm-up/measurement/profiling overhead, and
extend noisy runs. Report medians and variability, absolute units and relative differences; derive p95/p99 from
sufficient within-run samples. Include allocation, GC, retained/peak heap, cold latency and packet costs where relevant.
Confirm timing without profiling if overhead matters. A helper ratio is not an FPS/TPS claim.
Before editing, define the hypothesis, measured site and benefit above noise. Keep raw baselines and record commands,
commits, correctness checks, controls, regressions and acceptance decisions. Validate representative pack scenes after
consumer adoption. Below-noise results are valid; no fixed speedup target or speculative optimization is required.
The existing focused harness runs with an accepted local server EULA:
```powershell
.\gradlew.bat runFunctionalTestServer "-Pforgemultipart.profileFunctionalTests=true"
jfr summary run/server/forgemultipart-baseline.jfr
jfr view --width 220 hot-methods run/server/forgemultipart-baseline.jfr
jfr view thread-allocation run/server/forgemultipart-baseline.jfr
```
Profile mode overwrites ignored `run/server/forgemultipart-profile.txt` and `forgemultipart-baseline.jfr`.
The text's `startEpochMillis`/`nanos` identify phase windows; allocation counts use HotSpot per-thread counters.
Java 8 recordings expose TLAB events, not `ObjectAllocationSample`, so recent JDK `allocation-by-site` views are
not a valid summary. Consult `ForgeMultipartProfileWorkload` for current workload sizes and phases.
+156
View File
@@ -0,0 +1,156 @@
# Manual compatibility checklist
Behavior that the automated layers cannot assert. Plain-JVM tests cannot reach a world, a client or a renderer, and
the Forge server suite is headless, so everything below needs a human in a running client unless stated otherwise.
Each entry names what to do, what should happen, and which port put it here. Run the relevant entries before any
release that includes those ports.
Change `[ ]` to `[x]` after a successful check. If a check fails, leave it unchecked and add a dated note immediately
below its table.
Item examples below use English NEI names, checked against the supplied consumer clones' `en_US.lang` files and
registration code on 2026-09-03. Use the mod name to distinguish similarly named items. Sizes/colours add suffixes;
an OpenComputers print can have a custom label. Record the tested FMP build, pack version and item/setup with results.
For ProjectRed's external Scala-trait path, start with **Inverted White Lamp** (or another inverted colour), then saw
it into microblocks. `LightMicroMaterial.register` registers only lamp metadata 16–31; ordinary lamps and the
**White Illumar** crafting ingredient do not exercise this path. Useful resulting names include **Inverted White
Lamp Cover**, **Hollow Inverted White Lamp Cover**, **Inverted White Lamp Nook**, **Inverted White Lamp Strip** and
**Inverted White Lamp Post**.
## Rendering and particles
| Done | Check | Concrete example / setup | Expected | From |
| --- | --- | --- | --- | --- |
| [ ] | Break a cover or microblock part and watch the break overlay | Forge Multipart **Stone Cover** | The breaking texture is drawn on the part's own cuboid, not the full block | `TCuboidPart.drawBreaking` |
| [ ] | Hit a part repeatedly without breaking it | Forge Multipart **Grass Cover**; its top, side and bottom icons make a wrong face visible | Hit particles spawn on the struck face, using that face's icon | `IconHitEffects.addHitEffects` |
| [ ] | Break a part fully | ProjectRed Expansion **Solar Panel** placed horizontally; it has thin bounds and distinct top/side icons | Destroy particles query sides 0–5 and are scaled to the part's bounds | `IconHitEffects.addDestroyEffects` |
| [ ] | Break a hollow cover | Forge Multipart **Hollow Stone Cover** | Destroy particles use the full block bounds, not the part bounds | `addDestroyEffects` scaleDensity false |
| [ ] | Hover face, hollow, edge and corner microblock placement targets | Forge Multipart **Stone Cover**, **Hollow Stone Cover**, **Stone Strip** and **Stone Nook**; for a consumer override, hold a Stone Cover over ProjectRed **Framed Red Alloy Wire** to preview its jacket | The highlight and guide lines match each placement region, and a mod supplying its own highlight renderer overrides them | `PlacementGrid` / `MicroblockRender.renderHighlight` / `MicroblockEventHandler.drawBlockHighlight` / `MicroMaterialRegistry.renderHighlight` |
| [ ] | Reload client resources after placing several microblock materials | Place **Stone**, **Glass**, **Grass** and ProjectRed **Inverted White Lamp Covers**, then press `F3+T` | The texture atlas reloads every material icon without missing textures | `MicroblockEventHandler.postTextureStitch` / `BlockMicroMaterial.loadIcons` |
| [ ] | Render microblocks of a block whose icons another mod finishes in `TextureStitchEvent.Post` | Saw Chisel **Stone Bricks** variants that use `-v4` textures (2x2 submaps) into covers; check them on world load and again after `F3+T` | Covers show the Chisel texture, never the missing texture, both times | `BlockMicroMaterial.icont` stale re-resolve (GTNH issue 27183) |
| [ ] | Look at a **Stone Saw**, **Iron Saw** and **Diamond Saw** in inventory and in hand | All three items are supplied by Forge Multipart | The saw item renders with its custom transform | `ItemSaw` `IItemRenderer` |
| [ ] | Place microblocks of several materials, including glass | Compare Forge Multipart **Stone Cover** and **Glass Cover** | Transparent materials render in the correct pass and are not opaque | `BlockMicroMaterial` / `IMicroMaterial.canRenderInPass` |
| [ ] | Place grass and mycelium covers at several thicknesses and biomes | Forge Multipart **Grass Cover** and **Mycelium Cover**, preferably 1/8 and 1/2 thicknesses | Grass has an untinted base plus a tinted, height-aligned side overlay and tinted top; mycelium uses its top texture on horizontal faces and height-aligned side texture elsewhere | `GrassMicroMaterial` / `TopMicroMaterial` |
| [ ] | Load a saved microblock whose material is no longer installed | In a disposable instance, add `"minecraft:coal_ore"` to `microblocks.cfg`, create and save a **Coal Ore Cover**, remove that line, then reload | The part remains present and renders the magenta/black missing texture instead of becoming material ID 0 | `MissingMicroMaterial` |
| [ ] | Put a **Stone Cover** and a ProjectRed **Inverted White Lamp Cover** on opposite faces of one block space, then add/remove another part | Use another Stone Cover or ProjectRed **Red Alloy Wire** as the part that triggers cache updates | Static parts remain in the block render, dynamic parts remain in the TESR pass, and neither disappears after a part update | `TileMultipartClient` render caches |
| [ ] | Watch a multipart torch long enough to emit display particles | Add a **Stone Cover** to a vanilla **Torch** to convert it into a multipart; an active **Redstone Torch** is another useful case | Only parts implementing `IRandomDisplayTick` emit particles, with no duplicate or missing callbacks | `TRandomDisplayTickTile.randomDisplayTick` |
| [ ] | Start a client, join a server, place/update a multipart and use the multipart control key | Assign Forge Multipart's **Switch block disposition** key, then place and reorient a **Stone Cover** | Block and generated-tile rendering work, client packets arrive, and control-key state changes are sent once without duplicate registrations | `MultipartProxy_clientImpl.postInit` / `onTileClassBuilt` |
| [ ] | Move into view of a chunk containing several multipart tiles, then add, update and remove parts | Use mixed tiles containing an AE2 **ME Glass Cable**, a **Stone Cover**, and ProjectRed **Red Alloy Wire** on different faces | The initial chunk description reconstructs every tile and compressed updates apply without missing, duplicated or ghost parts | `MultipartCPH` / `MultipartSPH` |
| [ ] | Start a client with 3D saws enabled, inspect all three saw tiers and the microblock item, then repeat with Angelica installed | Set `useSawIcons=false`; inspect Forge Multipart's **Stone**, **Iron** and **Diamond Saws** and any Stone microblock | Each renderer is registered once, saw models use the correct tier, microblock icons load, client packets register, and the Angelica hook initializes without errors | `MicroblockProxy_clientImpl.init` / `postInit` |
| [ ] | Render several block micro-materials with Angelica shaders enabled, then render an unrelated block | Render **Stone**, **Grass** and **Glass Covers**, then an unrelated vanilla Stone block | Each face receives the matching block/meta shader material and the override is reset after the microblock draw | `MaterialRenderHelper.blockAndMeta` / `render` |
| [ ] | Inspect face, hollow, edge and corner microblocks in inventory and as dropped entities | Forge Multipart Stone **Cover**, **Hollow Cover**, **Strip**, **Post** and **Nook** at several sizes | Every size/material combination uses the correct localized name and centered shape/material render | `ItemMicroPart` / `ItemMicroPartRenderer` / `MicroblockRender.renderItem` |
| [ ] | Saw **Stone**, **Glass** and a ProjectRed **Inverted White Lamp** into face covers; place them on all six faces beside other microblocks, then inspect their inventory renders | The named Forge Multipart and ProjectRed microblocks are the concrete cases | Opaque covers retain their outer face while internal faces follow the shrink mask; transparent covers use the shrunk bounds, and inventory renders show the complete shape without missing or doubled faces | `FaceMicroblockClient.render` / `FaceMicroblockTraitLogic.render` |
| [ ] | Saw **Stone**, **Glass** and a ProjectRed **Inverted White Lamp** into strip/post shapes; place crossing posts on all three axes between face covers, then add and remove neighbours | The named Forge Multipart and ProjectRed microblocks are the concrete cases | Compare both split segments with the reference, including the second segment's use of physical bounds; removal resets the split without stale geometry or missing sections | `PostMicroblockClient.recalcBounds` / `PostMicroblockClientLogic` / `shrinkFace` / `shrinkPost` |
| [ ] | Run connected AE2 **ME Glass Cable**, **ME Covered Cable** and **ME Dense Smart Cable**, plus ProjectRed **Framed Red Alloy Wire**, through hollow stone/glass covers on all six faces | The named AE2, ProjectRed and Forge Multipart parts are the concrete cases | Each opening follows the connector size; opaque and transparent rims, breaking overlay and highlight have no missing, doubled or stale sections after neighbour changes | `HollowMicroblockClient` / `HollowMicroblockClientLogic` |
| [ ] | Place touching **Stone Cover**, **Glass Cover**, corner/edge counterparts and ProjectRed **Inverted White Lamp** microblocks at mixed sizes; add/remove neighbours, then rejoin the server | The named Forge Multipart and ProjectRed microblocks are the concrete cases | Intersections choose the same winner, opaque covered faces stay masked, and every surviving segment refreshes without gaps or stale bounds | `MicroOcclusion` / `TMicroOcclusionClient` / `TMicroOcclusionClientLogic` |
2026-09-03: Placing a ProjectRed part with `1.7.12-algent-java.186+60d060a3ff` crashed in
`MultipartRenderer$.renderTileEntityAt`: its class call to `TileMultipartClient.hasDynamicParts()` encountered the
transformed runtime interface. The renderer now calls the generated getter through a stable `TileMultipart` base
hook. Four headless Forge cases cover the actual renderer bytecode's guards and dispatch; both nonempty cases
reproduced the original crash. The user retested with the supplied fix and confirmed that placement no longer
crashes. Static/dynamic drawing and part updates still need their full client checks before marking the rendering
entries complete.
## Placement and interaction
| Done | Check | Concrete example / setup | Expected | From |
| --- | --- | --- | --- | --- |
| [ ] | Right-click a block face with ProjectRed **Red Alloy Wire** at a shallow angle | ProjectRed **Red Alloy Wire** | The part is placed in the clicked block | `TItemMultiPart.onItemUse` depth below 1 |
| [ ] | Repeat with **Red Alloy Wire**, clicking deep into a face | ProjectRed **Red Alloy Wire** | The part is placed in the neighbouring block on that side | `TItemMultiPart.onItemUse` offset path |
| [ ] | Place a part where it would overlap an existing one | Place a **Stone Cover**, then force a second Stone or Hollow Stone Cover into the same face slot using **Switch block disposition** if needed | Placement is refused rather than silently replacing | `NormalOcclusionTest`, `PartialOcclusionTest` |
| [ ] | Pass redstone through a hollow cover on a multipart face | Put ProjectRed **Framed Red Alloy Wire** in the centre and a **Hollow Stone Cover** between it and an external redstone source | Redstone still passes through the hollow centre | `TFacePart.redstoneConductionMap` |
| [ ] | Place **Hollow Stone Cover** and **Hollow Inverted White Lamp Cover** parts at several thicknesses around ProjectRed **Framed Red Alloy Wire** on all six faces; add/remove the wire, select the rim, then save and reload | The named Forge Multipart and ProjectRed parts are the concrete cases | The opening follows the connector, selection/collision respect the hollow centre, incompatible overlaps are refused, and shape/material survive reload | `HollowMicroblock` / `HollowMicroblockTraitLogic` |
| [ ] | Run ProjectRed **Red Alloy Wire** across a **Stone Strip** edge microblock | ProjectRed **Red Alloy Wire** and Forge Multipart **Stone Strip** | Conduction matches the pre-port behavior | `TEdgePart.conductsRedstone` |
| [ ] | Cut materials with saws of different harvest levels | Try **Stone Saw → Iron Block**, **Iron Saw → Diamond Block**, and **Diamond Saw → Obsidian**; confirm weaker saws reject the higher-tier cases | Only materials at or below the saw's strength can be cut | `Saw.getMaxCuttingStrength` |
| [ ] | Place the same microblock in survival and creative, including onto an existing multipart tile | Use a **Stone Cover** in empty space and beside ProjectRed **Framed Red Alloy Wire** | Valid placements play the material sound; survival consumes the expected amount while creative does not | `ItemMicroPart.onItemUse` |
| [ ] | With a second client watching, convert a vanilla torch by adding a cover, then add/remove compatible ProjectRed **Red Alloy Wire**, ProjectBlue **Control Panel**, or AE2 **ME Glass Cable** parts | Start with a vanilla **Torch + Stone Cover**, then use any named consumer part that fits | Both clients see each part exactly once, with no ghost block, stale render or missing part after tile replacement | `MultipartGenerator` conversion packet order and generated tile upgrade/downgrade |
## Downstream integration
| Done | Check | Concrete example / setup | Expected | From |
| --- | --- | --- | --- | --- |
| [ ] | Saw a ProjectRed **Inverted White Lamp** into cover, hollow cover, nook/corner and strip/post shapes; test face, corner, edge and centre-post placement | ProjectRed **Inverted White Lamp**; ordinary lamps and **White Illumar** do not exercise this registration path | The lamps generate, use the correct bounds, render and light correctly | `MicroblockGenerator.registerTrait` Scala trait path / shape factory facades |
| [ ] | Place and break OpenComputers **Cable** and a **3D Print**, ProjectBlue **Control Panel** (size suffix varies), and AE2 **ME Glass Cable**; share their block space with a compatible cover | Use a **Stone Cover** with each named consumer part | No `NoSuchMethodError` or `AbstractMethodError` in the log | retained `$class` bridges |
| [ ] | Load and render a schematic containing an ordered mixed multipart tile | Schematica; capture an AE2 **ME Glass Cable** with a **Stone Cover** and ProjectRed **Red Alloy Wire** on different faces | Every part appears in the preview in the saved order; the integration does not silently disable itself | `createPreviewTileFromNBT`, factory preview callbacks and `MultipartRenderer.renderWorldBlock` |
| [ ] | Open a GuideNH scene containing a multipart tile and export its part/material data | GuideNH; use the same **ME Glass Cable + Stone Cover + Red Alloy Wire** composite | The preview, material data and part statistics are complete | `createPreviewTileFromNBT`, typed part/material traversal and `MultipartRenderer.renderWorldBlock` |
| [ ] | Place FMP buttons on every supported face with Et Futurum loaded | Convert a vanilla **Stone Button** by adding a **Stone Cover**; repeat its supported orientations with Et Futurum Requiem installed | Button orientation matches the fixed vanilla behavior | supported `ButtonPart.setOrientation`; legacy arrays until consumer adoption |
| [ ] | With Iguana harvest-level tweaks enabled, inspect and use the Stone, Iron, Diamond, Ardite, Cobalt and Manyullyn saws against materials spanning their configured tiers | Forge Multipart supplies the first three saws; Iguana Tweaks for Tinkers' Construct supplies **Ardite**, **Cobalt** and **Manyullyn Saws** | Tooltips, saw textures and cutting recipes use the remapped tier; weaker saws do not gain the cached strongest-saw exemption | supported `ItemSaw.setHarvestLevel`; legacy field until consumer adoption |
| [ ] | Use OpenComputers **3D Printer** to make a **3D Print** with different off/on shapes that both fit beside a cover; place it with the cover and right-click to toggle | OpenComputers **3D Printer**, its resulting **3D Print**, and a Forge Multipart **Stone Cover** | Its slots are rebuilt without losing, hiding or disconnecting either part | external mutation of `TSlottedTile.v_partMap` plus `bindPart` |
| [ ] | Move the same composite tile using a ProjectRed **Frame Motor** with MCFrames **Frame** blocks, then a **Matter Manipulator MKIII** in move mode | Move the **ME Glass Cable + Stone Cover + Red Alloy Wire** composite with the named ProjectRed, MCFrames and Matter Manipulator items | Coordinates, part-to-tile references, generated interfaces and rendering remain correct after `onMoved` | ForgeRelocationFMP / MatterManipulator live multipart move lifecycle |
| [ ] | Capture and rebuild a mixed multipart tile with a BuildCraft **Builder**, then with a **Matter Manipulator MKIII** copy/paste | Blueprint and copy the **ME Glass Cable + Stone Cover + Red Alloy Wire** composite plus a Stone Strip, Hollow Cover and FMP torch or button; rebuild it elsewhere, rotated | Every part returns once with its material, shape, orientation and connections; microblocks land before other parts and no extra description packet is needed | Part `save`/`loadPart`, core type IDs and microblock NBT read by BuildCraftCompat and MatterManipulator |
| [ ] | Inspect a mixed multipart tile with Waila | Waila; inspect the **ME Glass Cable + Stone Cover + Red Alloy Wire** composite | Providers receive every saved part ID and show the expected part data | reflected block identity and tile NBT `parts`/`id` layout |
| [ ] | Spray ProjectRed wires that share blocks with covers, once normally and once sneaking to chain | GregTech **Spray Can** on ProjectRed **Insulated Wire** and **Bundled Cable** runs, each block also holding a **Stone Cover** placed before the wire | Only the struck wire, and when chaining its same-type neighbours, recolor; the cover is never selected | GT5U `BlockMultipart.reduceMOP` `Tuple2` index plus `jPartList`/`partMap` order |
| [ ] | Look at a ThaumicEnergistics vis interface on a covered AE2 cable with Waila | ThaumicEnergistics **Vis Relay Interface** part on an AE2 **ME Glass Cable** with a **Stone Cover** | The vis-link Waila lines still appear once the cover has turned the cable into a multipart tile | reflected `TileMultipart` class name plus AE2 part-host pass-through |
| [ ] | Load a world saved before the port | Use a pre-port save containing **Stone Covers**, ProjectRed lamp microblocks and an AE2 cable | All microblocks and covers keep their material and shape | `Microblock` shape/material NBT and `MicroMaterialRegistry` id map |
| [ ] | Join a server whose material set differs from the client | In disposable client/server instances, add `"minecraft:coal_ore"` only to the server's `microblocks.cfg` | The client is disconnected with the missing material list, not a crash | `readIDMap` |
| [ ] | Join a server whose multipart type set differs from the client | Setup-only: use a small test addon that registers a part on only one side; stock consumer removal may be rejected earlier by Forge's mod handshake | The client is disconnected with the ordered missing-part list, not a crash | `MultipartCPH.handlePartRegistration` |
The [Java illuminated extension example](../api/MICROBLOCK_EXTENSIONS.md) has dedicated-server and headless halo
coverage. When adopting it in ProjectRed, rerun the illuminated shape/lighting checks above on a physical client,
including hollow connector widths and all sides, pass filtering and the existing halo queue/configuration. Neither
its callback-side input tests nor its retained client-body probe validates actual client generation or GPU output.
## Not yet covered anywhere
- [ ] Follow the [performance protocol](MAINTAINERS.md#performance-validation); historical focused measurements are not full-pack evidence. A representative
full-pack capture and the matching post-optimization comparison still need to be performed. Example setup: a loaded
chunk containing many AE2 cables, ProjectRed wires/lamps and assorted Forge Multipart microblocks.
- [ ] Shape-specific microblock NBT and packet payloads. Core `Microblock` shape/material NBT, description bytes and
one-byte shape updates are complete, along with compact core tile/part NBT and logical chunk-description fixtures.
Example setup: Stone Cover, Hollow Cover, Nook, Strip and Post; save/rejoin and mutate each shape.
- [ ] Add UtilitiesInExcess as a compile/runtime fixture before it enters the pack: its `IPartFactory2`
registration, fence/wall/sphere parts and `getIdMap` / `materialCount` enumeration against the built port jar.
Fix its `mat` / `material` NBT key mismatch first; see the
[consumer finding](COMPATIBILITY.md#utilitiesinexcess---future-replacement-already-a-substantial-consumer).
## Item-name references
Resource paths below are relative to each consumer's `src/main/resources` in its source checkout.
Code locations identify the matching source packages/methods. Registration/behavior was checked in addition to
translation keys; these are examples for running the checks, not claims that the checks have passed.
| Consumer | Translation key / source |
| --- | --- |
| ProjectRed | `assets/projectred/lang/en_US.lang`: `tile.projectred.illumination.lamp\|16`, `item.projectred.transmission.wire\|0`, `framewire\|0`, `item.projectred.expansion.solar_panel`, `tile.projectred.expansion.machine2\|8`; `illumination/lightmicroblocks.scala` registers inverted lamp materials, `expansion/TileSolarPanel.scala` supplies a thin part with top/side particle icons, and `expansion/TileFrameMotor.scala` uses the relocation API |
| OpenComputers | `assets/opencomputers/lang/en_US.lang`: `tile.oc.cable`, `tile.oc.print`, `tile.oc.printer`; `integration/fmp/PrintPart.scala` toggles state and rebuilds slots |
| ProjectBlue | `assets/projectblue/lang/en_US.lang`: `item.gcewing_projectblue:controlPanel`; `ControlPanelItem.getItemStackDisplayName` appends its grid size |
| AE2 | `assets/appliedenergistics2/lang/en_US.lang`: `item.appliedenergistics2.ItemPart.CableGlass`, `CableCovered`, `CableDense`; `appeng/fmp/CableBusPart.getHollowSize` supplies connected cable bounds |
| ForgeRelocation / MatterManipulator | `assets/mcframes/lang/en_US.lang`: `tile.mcframes.frame`; `assets/matter-manipulator/lang/en_US.lang`: `item.itemMatterManipulator3`; the MKIII tier permits moving |
| Chisel | `compat/fmp/PartChiselTorch.java` and `FMPCompat.java`: any Chisel torch can be converted while preserving its variant and orientation |
| Iguana Tweaks for Tinkers' Construct | `modcompat/fmp`: Ardite, Cobalt and Manyullyn saws plus harvest-level remapping for Forge Multipart saws |
| FMP shapes and saws | This repository's `src/main/resources/assets/multipart/lang/en_US.lang`: `mcr_face`, `mcr_hllw`, `mcr_edge`, `mcr_cnr`, and `item.microblock:sawStone/sawIron/sawDiamond` |
## Converter integration follow-up
The [converter guide](../api/BLOCK_CONVERTERS.md) and Forge fixtures establish registration, discarded probes,
committed callback order and example state round trips. Before adopting consumer changes:
- [ ] On a physical client/server, preview and cancel conversion of Chisel torches, OpenComputers cables/prints,
AE2 cable buses and supported converter blocks; the source state/network must remain intact. Concrete cases: any
**Chisel Torch**, OpenComputers **Cable** and **3D Print**, and AE2 **ME Glass Cable**.
- [ ] Commit conversion, reconnect/reload, and confirm metadata, inventory and network state survive exactly once,
without duplicate drops, lost contents or ghost connections. Exercise rejection as well as successful placement
with the same Chisel, OpenComputers and AE2 cases.
- [ ] Recheck consumer side-specific constructors and descriptions; the headless example packet test does not cover
physical-client class selection or rendering. Record consumer release and actual pack adoption separately. Reuse
the Chisel Torch, OpenComputers Cable/3D Print and AE2 ME Glass Cable cases on both client and server.
## Stable tile capability adoption
- [ ] Rebuild ProjectRed's open-connection query against `IRedstoneTile`, retaining its rotation/mask logic; validate
face/framed wires with face covers and edge blockers on a physical client/server, including part changes and moves.
Concrete setup: ProjectRed **Red Alloy Wire** and **Framed Red Alloy Wire** with Stone Covers and Stone Strips.
- [ ] Verify consumer bytecode uses the stable interface/base owner rather than raw transformed trait class calls or
fields. The [Forge fixture](../api/TILE_TRAIT_ACCESS.md) proves server linkage, not all client-side capabilities.
This is a `javap`/ASM inspection check; no in-game item exercises the bytecode owner directly.
- [ ] Rebuild OpenComputers `PrintPart.toggleState` using `tile.refreshPartSlots(this)`, then exercise inactive/active
and button modes on client/server. Confirm old slots clear, new slots occupy, rejected changes leave caches intact,
and sound, part notification, description update and scheduled reset still occur once in the original order.
Concrete setup: an OpenComputers **3D Print** with different compact off/on shapes beside a Stone Cover.
- [ ] Verify the migrated OpenComputers bytecode no longer names `TSlottedTile`/`v_partMap`; retain the old accessor
until its released version is present in the target pack. This is also a `javap`/ASM inspection check, not an
additional in-game item test.
+71
View File
@@ -0,0 +1,71 @@
# ForgeMultipart migration status
The core runtime implementation and the audited consumer-facing Java replacements are implemented.
Consumer patches, released versions and target-pack adoption are still pending; API availability does not
mean a consumer has migrated. The first Java release retains supported legacy binaries and FMP's Scala bridges.
## Documentation
| Document | Purpose |
| --- | --- |
| [Java API](../API.md) and [release notes](../RELEASE_NOTES.md) | Supported replacements, examples and source migration hazards |
| [Compatibility audit](COMPATIBILITY.md) | Frozen ABI inventory, source revisions, reflective contracts and consumer findings |
| [Consumer adoption ledger](COMPATIBILITY.md#java-api-adoption-ledger) | Legacy contract, replacement, source patch, release and target-pack adoption |
| [Divergences](DIVERGENCES.md) | Intentional effective compatibility differences |
| [Manual release checks](MANUAL_CHECKS.md) | Outstanding client, pack and release validation |
| [Maintainer guide](MAINTAINERS.md) | Build boundaries, compiler constraints, verification and performance protocol |
Use this page for remaining work, not a running diary. Record consumer progress in the adoption ledger and
release results in the manual checklist. Completed-work narratives remain in git history. Test counts and
artifact inventories should come from the reports for the revision being reviewed.
## Remaining work
1. **Migrate consumers.** Use the existing typed APIs, with optional integrations gated on presence/version.
Preserve each consumer's state, ordering, failure policy and initialization timing. Record the source revision,
first released version, minimum FMP dependency and actual target-pack artifact for each legacy contract.
Consumer mods may remain Scala internally. Reference checkouts are not evidence of a shipped migration.
2. **Validate client and pack behavior.** Complete the manual checklist, including illuminated microblock
construction/halos, previews, rendering, particles, lighting, interactions, old worlds, multiplayer and movement.
Test optional dependencies both absent and present. The successful MCPC hook needs an actual patched World
where that platform is supported. Headless Forge tests do not establish GPU or full-pack correctness.
3. **Measure performance.** Once representative API/extension workloads are stable, profile realistic scenes and
make only justified changes. Separate FMP implementation gains from consumer API migration gains. Follow the
[measurement protocol](MAINTAINERS.md#performance-validation); historical focused results are not whole-pack claims.
4. **Finish repository/release preparation.** Relocate Java sources only where remaining Scala dependencies allow
it; reassess the forced Scala compilation/version guard after relocation, and update the root README's source
layout note. Validate Java 8 artifacts and packaged/obfuscated artifacts on the supported modern runtime. Modern syntax
expansion is optional and must respect the [build boundary](MAINTAINERS.md#build-and-runtime-boundaries).
5. **Remove FMP's Scala requirement last.** Complete the gates below before retiring bridges, compiler support
or dependencies. Other mods' independent Scala requirements are outside this target.
Extra Utilities 1.2.12 remains an active supported consumer. Switching support to UtilitiesInExcess requires an
explicit support decision and actual pack adoption, including migration of the replacement's FMP contracts.
GTNHLib/fastutil, Sponge Mixins and a replacement runtime generator are conditional choices, not migration tasks
in themselves. Add them only for a demonstrated need.
## Scala removal gates
- Every affected adoption-ledger row is verified against the actual target-pack jars, including reflective fields,
mixin targets, compiler-generated helpers and external Scala traits. Unmodifiable consumers must be retained or replaced.
- A deprecation/removal window and a release permitted to break the old ABI are agreed. That window is still open;
adding a replacement or deprecation is not permission to delete a bridge.
- FMP's own Scala storage, retained models, trait inputs and legacy callers are replaced or retired. In particular,
ProjectRed's released Java extension alone does not eliminate FMP's internal need for Scala-signature decoding.
- Shipped and generated FMP classes, descriptors and runtime loading paths contain no remaining Scala requirements;
Scala compilation and compiler/runtime dependencies can then be removed.
- Migrated consumers pass old-world, packet, client and dedicated-server validation against the resulting artifact.
## Retained implementation
| Sources under `src/main/scala/codechicken` | Remaining dependency |
| --- | --- |
| `multipart/asm/ASMMixinCompiler.scala` | Nested models, construction callbacks and Scala entry shell |
| `multipart/asm/ScalaSignature.scala` | Named models, primitive/erased bridges and generic inner construction |
| `multipart/asm/StackAnalyser.scala` | Coordinated class/companion/models, state and handler callbacks |
| `microblock/MicroblockTraits.scala`, `FaceMicroblockTraits.scala`, `CornerMicroblockTraits.scala`, `EdgeMicroblockTraits.scala` | State, inheritance, accessor and super-call shells over Java behavior |
| `microblock/HollowMicroblockTraits.scala`, `TMicroOcclusion.scala` | Server/client inheritance, initializers, state and lifecycle bridges |
Java sources also retain Scala-backed storage and compatibility references. A source-file count does not measure
removal readiness. Further extraction should enable a consumer migration, fix a demonstrated issue or provide a
measured benefit; mechanical shell conversion is not the next milestone.
+2 -24
View File
@@ -39,34 +39,13 @@ remoteMappings = https\://raw.githubusercontent.com/MinecraftForge/FML/1.7.10/co
# `./gradlew runClient --username=AnotherPlayer`, or configuring this command in your IDE.
developmentEnvironmentUserName = Developer
# Enables modern Java syntax support. Valid values:
# - false: No modern syntax, Java 8 only
# - jabel: Jabel syntax-only support, compiles to J8 bytecode
# - jvmDowngrader: Full modern Java via JVM Downgrader (syntax + stdlib APIs)
# - modern: Native modern Java bytecode, no downgrading
# Retained Scala and Java sources compile directly for Java 8.
enableModernJavaSyntax = false
# If set, ignores the above setting and compiles with the given toolchain. This may cause unexpected issues,
# and should *not* be used in most situations. -1 disables this.
# forceToolchainVersion = -1
# Target JVM version for JVM Downgrader bytecode downgrading.
# Only used when enableModernJavaSyntax = jvmDowngrader
# downgradeTargetVersion = 8
# Comma-separated list of Java versions for multi-release jar support (JVM Downgrader only).
# Classes will be available in META-INF/versions/N/ for each version N in this list.
# Default: "21,25" (J25+ gets native classes, J21-24 gets partial downgrade, J8-20 gets full downgrade).
# jvmDowngraderMultiReleaseVersions = 21,25
# Specifies how JVM Downgrader API stubs are provided. Options:
# - shade: Shade minimized stubs into the jar
# - gtnhlib: GTNHLib provides stubs at runtime (adds version constraint)
# - external: Another dependency provides stubs (no constraint, no warning)
# - (empty): Warning reminding you to configure stubs
# Note: 'shade' option requires you to verify license compliance, see: https://github.com/unimined/JvmDowngrader/blob/main/LICENSE.md
# jvmDowngraderStubsProvider =
# Enables injecting missing generics into the decompiled source code for a better coding experience.
# Turns most publicly visible List, Map, etc. into proper List<E>, Map<K, V> types.
enableGenericInjection = false
@@ -115,7 +94,7 @@ usesMixins = true
separateMixinSourceSet = mixin
# Adds some debug arguments like verbose output and class export.
usesMixinDebug = true
usesMixinDebug = false
# Specify the location of your implementation of IMixinConfigPlugin. Leave it empty otherwise.
mixinPlugin =
@@ -237,4 +216,3 @@ curseForgeRelations =
# Whether IDEA should run spotless checks when pressing the Build button.
# This is meant to be set in $HOME/.gradle/gradle.properties.
# ideaCheckSpotlessOnBuild = true
-1
View File
@@ -1,5 +1,4 @@
// Add any additional repositiroes for your dependencies here
repositories {
mavenLocal()
}
@@ -0,0 +1,86 @@
package codechicken.multipart.examples;
import java.util.Collections;
import net.minecraft.block.Block;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import codechicken.lib.data.MCDataInput;
import codechicken.lib.data.MCDataOutput;
import codechicken.lib.vec.BlockCoord;
import codechicken.multipart.MultiPartRegistry;
import codechicken.multipart.MultiPartRegistry.IPartConverter;
import codechicken.multipart.MultiPartRegistry.IPartFactory2;
import codechicken.multipart.TMultiPart;
/** Compiling registration/state example; add the real part's geometry, rendering and gameplay behavior. */
public final class BlockConversionExample implements IPartConverter, IPartFactory2 {
public static final String PART_TYPE = "yourmod:converted";
private final Block sourceBlock;
public BlockConversionExample(Block sourceBlock) {
this.sourceBlock = sourceBlock;
}
/** Call once from common preInit/init, after registering the source block, on both sides. */
public static void register(Block sourceBlock) {
BlockConversionExample example = new BlockConversionExample(sourceBlock);
MultiPartRegistry.registerPartFactory(example, PART_TYPE);
MultiPartRegistry.registerConverter(example);
}
@Override
public Iterable<Block> blockTypes() {
return Collections.singletonList(sourceBlock);
}
@Override
public TMultiPart convert(World world, BlockCoord pos) {
if (world.getBlock(pos.x, pos.y, pos.z) != sourceBlock) return null;
ConvertedPart part = new ConvertedPart();
part.metadata = world.getBlockMetadata(pos.x, pos.y, pos.z);
return part;
}
@Override
public TMultiPart createPart(String name, NBTTagCompound nbt) {
return new ConvertedPart();
}
@Override
public TMultiPart createPart(String name, MCDataInput packet) {
return new ConvertedPart();
}
public static final class ConvertedPart extends TMultiPart {
private int metadata;
@Override
public String getType() {
return PART_TYPE;
}
@Override
public void save(NBTTagCompound tag) {
tag.setInteger("metadata", metadata);
}
@Override
public void load(NBTTagCompound tag) {
metadata = tag.getInteger("metadata");
}
@Override
public void writeDesc(MCDataOutput packet) {
packet.writeInt(metadata);
}
@Override
public void readDesc(MCDataInput packet) {
metadata = packet.readInt();
}
}
}
@@ -0,0 +1,22 @@
package codechicken.multipart.examples;
import net.minecraftforge.common.util.ForgeDirection;
import codechicken.multipart.minecraft.ButtonPart;
/** Forge-tested compiling example for docs/api/BUTTON_ORIENTATIONS.md. */
public final class ButtonOrientationExample {
private ButtonOrientationExample() {}
/** Enables the floor and ceiling metadata supplied by Et Futurum Requiem's button extension. */
public static void registerVerticalOrientations() {
ButtonPart.setOrientation(0, ForgeDirection.UP);
ButtonPart.setOrientation(5, ForgeDirection.DOWN);
}
/** Looks up a custom button's metadata without changing its placement or construction policy. */
public static int metadataForClickedFace(int side) {
return ButtonPart.metaForSide(side ^ 1);
}
}
@@ -0,0 +1,29 @@
package codechicken.multipart.examples;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import codechicken.multipart.MultipartHelper;
import codechicken.multipart.MultipartRenderer;
import codechicken.multipart.TileMultipart;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
/** Compiling example for constructing and rendering an uninstalled multipart preview without reflection or Scala. */
@SideOnly(Side.CLIENT)
public final class ClientPreviewExample {
private ClientPreviewExample() {}
public static TileMultipart create(World clientWorld, NBTTagCompound savedTile) {
return MultipartHelper.createPreviewTileFromNBT(clientWorld, savedTile);
}
public static boolean render(IBlockAccess world, int x, int y, int z, Block multipartBlock, RenderBlocks renderer) {
return MultipartRenderer
.renderWorldBlock(world, x, y, z, multipartBlock, multipartBlock.getRenderType(), renderer);
}
}
@@ -0,0 +1,31 @@
package codechicken.multipart.examples;
import java.util.List;
import net.minecraft.world.World;
import codechicken.lib.vec.BlockCoord;
import codechicken.multipart.MultipartGenerator;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TileMultipart;
/** Forge-tested compiling example for docs/api/COMPOSITE_GENERATION.md. */
public final class CompositeGenerationExample {
private CompositeGenerationExample() {}
/**
* Prepares and loads a fresh tile without installing it. Parts must already be loaded and appropriate for the
* requested side. A supplied world must agree with that side; null is allowed for worldless staging.
*/
public static TileMultipart createUninstalledTile(World world, BlockCoord pos, List<TMultiPart> parts,
boolean client) {
TileMultipart tile = MultipartGenerator.generateCompositeTile(null, parts, client);
tile.xCoord = pos.x;
tile.yCoord = pos.y;
tile.zCoord = pos.z;
tile.setWorldObj(world);
tile.loadPartList(parts);
return tile;
}
}
@@ -0,0 +1,28 @@
package codechicken.multipart.examples;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TileMultipart;
/** Register by name before loading this Java class; FMP transforms it into a runtime trait interface. */
public abstract class CustomTileTrait extends TileMultipart implements CustomTileTraitCapability {
@Override
public int totalContribution() {
return CustomTileTraitAccess.totalContribution(this);
}
}
final class CustomTileTraitAccess {
private CustomTileTraitAccess() {}
static int totalContribution(Object trait) {
int total = 0;
for (TMultiPart part : ((TileMultipart) trait).jPartList()) {
if (part instanceof CustomTileTraitPart) {
total += ((CustomTileTraitPart) part).tileContribution();
}
}
return total;
}
}
@@ -0,0 +1,7 @@
package codechicken.multipart.examples;
/** Stable consumer-facing API implemented by generated tiles carrying {@link CustomTileTraitPart} parts. */
public interface CustomTileTraitCapability {
int totalContribution();
}
@@ -0,0 +1,22 @@
package codechicken.multipart.examples;
import codechicken.multipart.MultipartGenerator;
import codechicken.multipart.TileMultipart;
/** Compiling registration and access example for a consumer-owned generated tile trait. */
public final class CustomTileTraitExample {
private static final String TRAIT = "codechicken.multipart.examples.CustomTileTrait";
private CustomTileTraitExample() {}
/** Call once during mod initialization, before FMP inspects any implementing part class. */
public static void register() {
MultipartGenerator.registerTrait(CustomTileTraitPart.class.getName(), TRAIT);
}
/** Read through the stable capability interface; tiles without the custom trait contribute zero. */
public static int totalContribution(TileMultipart tile) {
return tile instanceof CustomTileTraitCapability ? ((CustomTileTraitCapability) tile).totalContribution() : 0;
}
}
@@ -0,0 +1,7 @@
package codechicken.multipart.examples;
/** Marker and contribution contract for parts that request the example generated tile trait. */
public interface CustomTileTraitPart {
int tileContribution();
}
@@ -0,0 +1,30 @@
package codechicken.multipart.examples;
import java.util.BitSet;
import net.minecraft.block.Block;
import codechicken.microblock.BlockMicroMaterial;
import codechicken.microblock.MicroblockClass;
import codechicken.microblock.MicroblockGenerator.IGeneratedMaterial;
/** Example material whose upper metadata bit means illuminated and low bits select the lamp colour. */
public final class IlluminatedMicroMaterial extends BlockMicroMaterial implements IGeneratedMaterial {
private final int traitId;
public IlluminatedMicroMaterial(Block lamp, int meta, int traitId) {
super(lamp, meta);
this.traitId = traitId;
}
@Override
public void addTraits(BitSet traits, MicroblockClass microClass, boolean client) {
traits.set(traitId);
}
@Override
public int getCutterStrength() {
return block().getHarvestLevel(meta() % 16);
}
}
@@ -0,0 +1,122 @@
package codechicken.multipart.examples;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BooleanSupplier;
import net.minecraft.block.Block;
import codechicken.lib.vec.Cuboid6;
import codechicken.lib.vec.Rotation;
import codechicken.lib.vec.Transformation;
import codechicken.lib.vec.Vector3;
import codechicken.microblock.BlockMicroMaterial;
import codechicken.microblock.HollowMicroblock;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.Microblock;
import codechicken.microblock.MicroblockGenerator;
import codechicken.multipart.TMultiPart;
/** Compiling example for docs/api/MICROBLOCK_EXTENSIONS.md; the consumer supplies its config and halo renderer. */
public final class IlluminatedMicroblockExample {
public static BooleanSupplier dimLampParts = () -> false;
/**
* Install on the physical client before rendering, e.g. a lambda forwarding to ProjectRed's RenderHalo.addLight.
*/
public static HaloRenderer haloRenderer;
public interface HaloRenderer {
void addLight(int x, int y, int z, int colour, Cuboid6 bounds);
}
private IlluminatedMicroblockExample() {}
/** Call once during mod initialization, after the lamp block is registered and before FMP builds material IDs. */
public static void registerMaterials(Block lamp) {
int traitId = MicroblockGenerator.registerTrait("codechicken.multipart.examples.IlluminatedMicroblockTrait");
for (int meta = 16; meta < 32; meta++) {
MicroMaterialRegistry.registerMaterial(
new IlluminatedMicroMaterial(lamp, meta, traitId),
BlockMicroMaterial.materialKey(lamp, meta));
}
}
/** Object is deliberate: the transformed trait interface does not inherit Microblock in the JVM type system. */
public static int lightValue(Object trait) {
Microblock part = (Microblock) trait;
if (dimLampParts.getAsBoolean()) {
// Capture matching parts before size callbacks, as the reference's strict collection pipeline does.
List<Microblock> selected = new ArrayList<>();
for (TMultiPart sibling : part.tile().jPartList()) {
if (sibling instanceof IlluminatedMicroblockTrait) selected.add((Microblock) sibling);
}
double total = 0;
for (Microblock sibling : selected) total += sibling.getSize() / 8D;
return Math.min(15, (int) (15 * total));
}
for (TMultiPart sibling : part.tile().jPartList()) {
if (sibling instanceof IlluminatedMicroblockTrait) return 15;
}
return 0;
}
/** Halo submission is a client responsibility; the geometry itself is headlessly testable. */
public static void renderHalo(Object trait, int pass) {
if (pass != 0) return;
Microblock part = (Microblock) trait;
List<Cuboid6> boxes = haloBoxes(part);
int colour = ((IlluminatedMicroMaterial) part.getIMaterial()).meta() - 16;
for (Cuboid6 box : boxes) haloRenderer.addLight(part.x(), part.y(), part.z(), colour, box);
}
public static List<Cuboid6> haloBoxes(Microblock part) {
double expansion = 0.025;
if (part instanceof HollowMicroblock) {
int size = ((HollowMicroblock) part).getHollowSize();
double near = 0.5 - size / 32D;
double far = 0.5 + size / 32D;
double thickness = (part.shape() >> 4) / 8D;
Transformation rotation = Rotation.sideRotations[part.shape() & 15].at(Vector3.center);
List<Cuboid6> boxes = Arrays.asList(
new Cuboid6(
-expansion,
-expansion,
-expansion,
1 + expansion,
thickness + expansion,
near + expansion),
new Cuboid6(
-expansion,
-expansion,
far - expansion,
1 + expansion,
thickness + expansion,
1 + expansion),
new Cuboid6(
-expansion,
-expansion,
near + expansion,
near + expansion,
thickness + expansion,
far - expansion),
new Cuboid6(
far - expansion,
-expansion,
near + expansion,
1 + expansion,
thickness + expansion,
far - expansion));
for (Cuboid6 box : boxes) box.apply(rotation);
return boxes;
}
List<Cuboid6> source = new ArrayList<>();
for (Cuboid6 box : part.getCollisionBoxes()) source.add(box);
List<Cuboid6> expanded = new ArrayList<>();
for (Cuboid6 box : source) expanded.add(box.copy().expand(expansion));
return expanded;
}
}
@@ -0,0 +1,30 @@
package codechicken.multipart.examples;
import codechicken.lib.vec.Vector3;
import codechicken.microblock.Microblock;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
/** Register by name before loading this Java class; FMP transforms it into a runtime trait interface. */
public abstract class IlluminatedMicroblockTrait extends Microblock {
public IlluminatedMicroblockTrait() {
super(0);
}
@Override
public boolean shouldRenderDynamic() {
return true;
}
@Override
public int getLightValue() {
return IlluminatedMicroblockExample.lightValue(this);
}
@Override
@SideOnly(Side.CLIENT)
public void renderDynamic(Vector3 pos, float frame, int pass) {
IlluminatedMicroblockExample.renderHalo(this, pass);
}
}
@@ -0,0 +1,38 @@
package codechicken.multipart.examples;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.tileentity.TileEntity;
import codechicken.microblock.BlockMicroMaterial;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.MicroMaterialRegistry.IMicroMaterial;
import codechicken.microblock.Microblock;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TileMultipart;
/** Forge-tested compiling example for docs/api/MATERIAL_ACCESS.md. */
public final class MaterialAccessExample {
private MaterialAccessExample() {}
/** Returns the first usable block ID using GuideNH's metadata suffix policy; failures propagate to the caller. */
public static String resolvePrimaryMicroblockId(TileEntity tile) {
if (!(tile instanceof TileMultipart)) return null;
for (TMultiPart part : ((TileMultipart) tile).jPartList()) {
if (!(part instanceof Microblock)) continue;
IMicroMaterial material = MicroMaterialRegistry.getMaterial(((Microblock) part).material());
if (!(material instanceof BlockMicroMaterial)) continue;
BlockMicroMaterial blockMaterial = (BlockMicroMaterial) material;
Block block = blockMaterial.block();
int meta = blockMaterial.meta();
if (block == null || block == Blocks.air) continue;
Object registryName = Block.blockRegistry.getNameForObject(block);
if (registryName == null) continue;
String blockId = registryName.toString();
if (blockId.isEmpty()) continue;
return meta > 0 ? blockId + ":" + meta : blockId;
}
return null;
}
}
@@ -0,0 +1,21 @@
package codechicken.multipart.examples;
import codechicken.microblock.Microblock;
import codechicken.microblock.MicroblockClass;
import codechicken.microblock.MicroblockGenerator;
/** Forge-tested compiling example for docs/api/MICROBLOCK_CREATION.md. */
public final class MicroblockCreationExample {
private MicroblockCreationExample() {}
/** Recreates the family/material/shape on the requested side; does not clone other custom state or bindings. */
public static Microblock recreateForSide(Microblock source, boolean client) {
MicroblockClass microClass = source.microClass();
int material = source.material();
byte shape = source.shape();
Microblock created = MicroblockGenerator.create(microClass, material, client);
created.setShape(shape >> 4, shape & 0xF);
return created;
}
}
@@ -0,0 +1,21 @@
package codechicken.multipart.examples;
import codechicken.microblock.Microblock;
import codechicken.microblock.MicroblockClass;
import codechicken.multipart.MultiPartRegistry;
import codechicken.multipart.MultiPartRegistry.IPartFactory2;
/** Forge-tested compiling example for docs/api/FACTORY_LOOKUP.md. */
public final class PartFactoryLookupExample {
private PartFactoryLookupExample() {}
/** Creates an unbound microblock; the caller still loads its NBT and prepares the containing tile. */
public static Microblock createMicroblock(String type, boolean client, int material) {
IPartFactory2 factory = MultiPartRegistry.getPartFactory(type);
if (!(factory instanceof MicroblockClass)) {
return null;
}
return ((MicroblockClass) factory).create(client, material);
}
}
@@ -0,0 +1,105 @@
package codechicken.multipart.examples;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import codechicken.lib.data.MCDataInput;
import codechicken.lib.data.MCDataOutput;
import codechicken.lib.vec.BlockCoord;
import codechicken.multipart.MultiPartRegistry;
import codechicken.multipart.MultiPartRegistry.IPartFactory2;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TileMultipart;
/** Compiling example for the part-registration and custom-part lifecycle guides. */
public final class PartRegistrationExample implements IPartFactory2 {
public static final String PART_TYPE = "yourmod:part";
/** Call from the mod's common preInit/init handler, on both sides. */
public static void register() {
MultiPartRegistry.registerPartFactory(new PartRegistrationExample(), PART_TYPE);
}
@Override
public TMultiPart createPart(String name, NBTTagCompound nbt) {
return new ExamplePart();
}
@Override
public TMultiPart createPart(String name, MCDataInput packet) {
return new ExamplePart();
}
@Override
public TMultiPart createPartForClientPreview(String name, NBTTagCompound nbt) {
return new ExamplePart();
}
/** Call from the server-side item/action after choosing the target position. */
public static TileMultipart place(World world, BlockCoord pos, int value) {
ExamplePart part = new ExamplePart(value);
if (world.isRemote || !TileMultipart.canPlacePart(world, pos, part)) {
return null;
}
return TileMultipart.addPart(world, pos, part);
}
public static final class ExamplePart extends TMultiPart {
private int value;
public ExamplePart() {}
public ExamplePart(int value) {
this.value = value;
}
@Override
public String getType() {
return PART_TYPE;
}
@Override
public boolean doesTick() {
return false;
}
public int value() {
return value;
}
/** Example for state that affects persistence, clients, sibling parts and rendering. */
public void setValue(int value) {
if (this.value == value) {
return;
}
this.value = value;
if (world() != null && !world().isRemote) {
sendDescUpdate();
tile().notifyPartChange(this);
tile().markDirty();
}
}
@Override
public void save(NBTTagCompound tag) {
tag.setInteger("value", value);
}
@Override
public void load(NBTTagCompound tag) {
value = tag.getInteger("value");
}
@Override
public void writeDesc(MCDataOutput packet) {
packet.writeInt(value);
}
@Override
public void readDesc(MCDataInput packet) {
value = packet.readInt();
}
}
}
@@ -0,0 +1,19 @@
package codechicken.multipart.examples;
import net.minecraft.world.World;
import codechicken.lib.vec.BlockCoord;
import codechicken.multipart.TileConversionResult;
import codechicken.multipart.TileMultipart;
/** Forge-tested compiling example for docs/api/TILE_CONVERSION.md. */
public final class TileConversionExample {
private TileConversionExample() {}
/** Returns only a newly converted placeholder, for inspection without installing it. */
public static TileMultipart findConvertedPlaceholder(World world, BlockCoord pos) {
TileConversionResult result = TileMultipart.getOrConvertTileResult(world, pos);
return result.isConverted() ? result.getTile() : null;
}
}
@@ -0,0 +1,26 @@
package codechicken.multipart.examples;
import codechicken.multipart.IRedstoneTile;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TileMultipart;
/** Compiling consumer example using a stable capability instead of the raw transformed trait class. */
public final class TileTraitAccessExample {
private TileTraitAccessExample() {}
/** Returns false for null/non-redstone tiles; side is 0..5 and mask uses the low five connection bits. */
public static boolean hasOpenConnection(TileMultipart tile, int side, int mask) {
return tile instanceof IRedstoneTile && (((IRedstoneTile) tile).openConnections(side) & mask) != 0;
}
/** Call after a stored part has validated and applied a new slot mask, before its own notifications. */
public static void refreshSlots(TileMultipart tile, TMultiPart part) {
tile.refreshPartSlots(part);
}
/** Call after a stored inventory part changes its size, before notifying neighbors; no-op without inventories. */
public static void refreshInventory(TileMultipart tile) {
tile.refreshInventorySlots();
}
}
@@ -0,0 +1,299 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.*;
import static org.objectweb.asm.Opcodes.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.MethodNode;
import codechicken.multipart.asm.ASMMixinCompiler;
import codechicken.multipart.asm.ASMMixinCompiler$;
import codechicken.multipart.asm.ASMMixinCompiler.MixinInfo;
import scala.Tuple2;
class ASMBridgeFunctionalTest {
@Test
void splitsAtTheFirstParenthesisWithoutValidatingTheDescriptor() {
assertEquals(
new Tuple2<>("method", "(JD)Ljava/lang/String;"),
ASMMixinCompiler.seperateDesc("method(JD)Ljava/lang/String;"));
assertEquals(new Tuple2<>("", "()V"), ASMMixinCompiler$.MODULE$.seperateDesc("()V"));
assertEquals(
new Tuple2<>("odd.name", "(not(a descriptor"),
ASMMixinCompiler.seperateDesc("odd.name(not(a descriptor"));
assertThrows(StringIndexOutOfBoundsException.class, () -> ASMMixinCompiler.seperateDesc("missing"));
assertThrows(StringIndexOutOfBoundsException.class, () -> ASMMixinCompiler.seperateDesc(""));
assertThrows(NullPointerException.class, () -> ASMMixinCompiler.seperateDesc(null));
}
@Test
void prependsAnObjectReceiverAndPreservesAllArgumentAndReturnTypes() {
for (String result : new String[] { "V", "Z", "B", "C", "S", "I", "F", "J", "D", "Ljava/lang/Object;",
"[[I" }) {
assertEquals("(Ltest/Owner;)" + result, ASMMixinCompiler.staticDesc("test/Owner", "()" + result));
assertEquals(
"(Ltest/Owner;ZBCSIFJD[ILjava/lang/String;[[D)" + result,
ASMMixinCompiler$.MODULE$.staticDesc("test/Owner", "(ZBCSIFJD[ILjava/lang/String;[[D)" + result));
}
assertEquals("(Ltest.Owner;)V", ASMMixinCompiler.staticDesc("test.Owner", "()V"));
assertEquals("(Lnull;)V", ASMMixinCompiler.staticDesc(null, "()V"));
assertEquals("(L;)V", ASMMixinCompiler.staticDesc("", "()V"));
assertThrows(NullPointerException.class, () -> ASMMixinCompiler.staticDesc("test/Owner", null));
assertThrows(ArrayIndexOutOfBoundsException.class, () -> ASMMixinCompiler.staticDesc("test/Owner", "()"));
}
@Test
void loadsMixedArgumentsInSlotOrderAndUsesTheBridgeDescriptorForItsReturnAndMaxima() {
Trace trace = new Trace();
ASMMixinCompiler.writeBridge(
trace,
"(ZBCSIFJD[ILjava/lang/String;[[D)D",
INVOKESTATIC,
"test/Helper",
"target",
"(Ljava/lang/Object;)V");
assertEquals(
Arrays.asList(
"var " + ALOAD + " 0",
"var " + ILOAD + " 1",
"var " + ILOAD + " 2",
"var " + ILOAD + " 3",
"var " + ILOAD + " 4",
"var " + ILOAD + " 5",
"var " + FLOAD + " 6",
"var " + LLOAD + " 7",
"var " + DLOAD + " 9",
"var " + ALOAD + " 11",
"var " + ALOAD + " 12",
"var " + ALOAD + " 13",
"call " + INVOKESTATIC + " test/Helper target (Ljava/lang/Object;)V false",
"insn " + DRETURN,
"max 14 14"),
trace.events);
}
@Test
void handlesEveryReturnCategoryIncludingWideResultsWithoutArguments() {
String[] returns = { "V", "Z", "B", "C", "S", "I", "F", "J", "D", "Ljava/lang/Object;", "[J" };
int[] opcodes = { RETURN, IRETURN, IRETURN, IRETURN, IRETURN, IRETURN, FRETURN, LRETURN, DRETURN, ARETURN,
ARETURN };
int[] stacks = { 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1 };
for (int i = 0; i < returns.length; i++) {
Trace trace = new Trace();
String desc = "()" + returns[i];
ASMMixinCompiler.finishBridgeCall(trace, desc, INVOKEVIRTUAL, "test/Owner", "value", desc);
assertEquals(
Arrays.asList(
"call " + INVOKEVIRTUAL + " test/Owner value " + desc + " false",
"insn " + opcodes[i],
"max " + stacks[i] + " 1"),
trace.events,
desc);
}
}
@Test
void derivesTheInterfaceFlagOnlyFromTheInvocationOpcodeAndLeavesTheReceiverToTheCaller() {
for (int opcode : new int[] { INVOKEVIRTUAL, INVOKESPECIAL, INVOKESTATIC, INVOKEINTERFACE }) {
Trace trace = new Trace();
trace.visitVarInsn(ALOAD, 0);
trace.visitFieldInsn(GETFIELD, "test/Wrapper", "delegate", "Ltest/Contract;");
ASMMixinCompiler$.MODULE$.finishBridgeCall(trace, "(J)I", opcode, "test/Contract", "call", "(J)I");
assertEquals(
Arrays.asList(
"var " + ALOAD + " 0",
"field " + GETFIELD + " test/Wrapper delegate Ltest/Contract;",
"var " + LLOAD + " 1",
"call " + opcode + " test/Contract call (J)I " + (opcode == INVOKEINTERFACE),
"insn " + IRETURN,
"max 3 3"),
trace.events);
}
}
@Test
void preservesPartialVisitorOutputAndPropagatesTheOriginalFailure() {
Trace completed = new Trace();
ASMMixinCompiler.writeBridge(completed, "(JD)I", INVOKEVIRTUAL, "test/Owner", "call", "(JD)I");
for (int event = 1; event <= completed.events.size(); event++) {
Trace failing = new Trace();
failing.failAt = event;
assertSame(
failing.failure,
assertThrows(
IllegalStateException.class,
() -> ASMMixinCompiler
.writeBridge(failing, "(JD)I", INVOKEVIRTUAL, "test/Owner", "call", "(JD)I")));
assertEquals(completed.events.subList(0, event), failing.events);
}
Trace finish = new Trace();
assertThrows(
NullPointerException.class,
() -> ASMMixinCompiler.finishBridgeCall(finish, null, INVOKEVIRTUAL, "owner", "name", "()V"));
assertTrue(finish.events.isEmpty());
Trace bridge = new Trace();
assertThrows(
NullPointerException.class,
() -> ASMMixinCompiler.writeBridge(bridge, null, INVOKEVIRTUAL, "owner", "name", "()V"));
assertEquals(Arrays.asList("var " + ALOAD + " 0"), bridge.events);
}
@Test
void staticBridgeReadsOverridableMixinMetadataAndDescriptorsInTheOriginalOrder() {
MethodNode method = new MethodNode(ACC_PUBLIC, "bridge", "(I)I", null, null);
List<String> reads = new ArrayList<>();
MixinInfo mixin = new MixinInfo("unused", null, null, null, null, null) {
@Override
public String tname() {
reads.add("helper:" + method.desc);
method.desc = "(J)J";
return "test/Helper";
}
@Override
public String name() {
reads.add("receiver:" + method.desc);
method.desc = "(D)D";
return "test/Receiver";
}
};
ASMMixinCompiler.writeStaticBridge(method, "target", mixin);
Trace trace = new Trace();
method.accept(trace);
assertEquals(Arrays.asList("helper:(I)I", "receiver:(J)J"), reads);
assertEquals(
Arrays.asList(
"var " + ALOAD + " 0",
"var " + ILOAD + " 1",
"call " + INVOKESTATIC + " test/Helper target (Ltest/Receiver;D)D false",
"insn " + IRETURN,
"max 2 2"),
trace.events);
assertThrows(NullPointerException.class, () -> ASMMixinCompiler.writeStaticBridge(method, "target", null));
}
@Test
void emittedBridgesExecuteVirtualSpecialInterfaceAndScalaStyleStaticDispatch() throws Exception {
String parent = Type.getInternalName(Receiver.class);
String owner = "codechicken/multipart/test/bridge/ExecutableBridge";
ClassWriter writer = new ClassWriter(0);
writer.visit(V1_6, ACC_PUBLIC, owner, null, parent, null);
MethodVisitor constructor = writer.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
ASMMixinCompiler.writeBridge(constructor, "()V", INVOKESPECIAL, parent, "<init>", "()V");
constructor.visitEnd();
MethodVisitor value = writer.visitMethod(ACC_PUBLIC, "value", "()I", null, null);
value.visitIntInsn(BIPUSH, 99);
value.visitInsn(IRETURN);
value.visitMaxs(1, 1);
value.visitEnd();
addBridge(writer, "viaVirtual", "()I", INVOKEVIRTUAL, parent, "value");
addBridge(writer, "viaSpecial", "()I", INVOKESPECIAL, parent, "value");
String desc = "(JDLjava/lang/String;[I)Ljava/lang/String;";
addBridge(writer, "viaInterface", desc, INVOKEINTERFACE, Type.getInternalName(Contract.class), "combine");
MethodNode staticBridge = new MethodNode(ACC_PUBLIC, "viaStatic", desc, null, null);
ASMMixinCompiler
.writeStaticBridge(staticBridge, "combine", new MixinInfo(parent, null, null, null, null, null));
staticBridge.accept(writer);
writer.visitEnd();
byte[] bytes = writer.toByteArray();
Class<?> generated = new ClassLoader(getClass().getClassLoader()) {
Class<?> define() {
return defineClass(null, bytes, 0, bytes.length);
}
}.define();
Object receiver = generated.getConstructor().newInstance();
assertEquals(99, generated.getMethod("viaVirtual").invoke(receiver));
assertEquals(17, generated.getMethod("viaSpecial").invoke(receiver));
Class<?>[] parameters = { long.class, double.class, String.class, int[].class };
assertEquals(
"instance:99:1234567890123:2.5:abc:7",
generated.getMethod("viaInterface", parameters)
.invoke(receiver, 1234567890123L, 2.5, "abc", new int[] { 7 }));
assertEquals(
"static:99:1234567890123:2.5:abc:7",
generated.getMethod("viaStatic", parameters)
.invoke(receiver, 1234567890123L, 2.5, "abc", new int[] { 7 }));
}
private static void addBridge(ClassWriter writer, String name, String desc, int opcode, String owner,
String target) {
MethodVisitor method = writer.visitMethod(ACC_PUBLIC, name, desc, null, null);
ASMMixinCompiler.writeBridge(method, desc, opcode, owner, target, desc);
method.visitEnd();
}
private static class Trace extends MethodVisitor {
final List<String> events = new ArrayList<>();
final IllegalStateException failure = new IllegalStateException("visitor failure");
int failAt;
Trace() {
super(ASM5);
}
private void record(String event) {
events.add(event);
if (events.size() == failAt) throw failure;
}
@Override
public void visitVarInsn(int opcode, int local) {
record("var " + opcode + " " + local);
}
@Override
public void visitFieldInsn(int opcode, String owner, String name, String desc) {
record("field " + opcode + " " + owner + " " + name + " " + desc);
}
@Override
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
record("call " + opcode + " " + owner + " " + name + " " + desc + " " + itf);
}
@Override
public void visitInsn(int opcode) {
record("insn " + opcode);
}
@Override
public void visitMaxs(int stack, int locals) {
record("max " + stack + " " + locals);
}
}
public interface Contract {
String combine(long wide, double number, String text, int[] array);
}
public static class Receiver implements Contract {
public int value() {
return 17;
}
@Override
public String combine(long wide, double number, String text, int[] array) {
return "instance:" + value() + ":" + wide + ":" + number + ":" + text + ":" + array[0];
}
}
public static class Receiver$class {
public static String combine(Receiver receiver, long wide, double number, String text, int[] array) {
return "static:" + receiver.value() + ":" + wide + ":" + number + ":" + text + ":" + array[0];
}
}
}
@@ -0,0 +1,167 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.*;
import static org.objectweb.asm.Opcodes.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.HashMap;
import java.util.Set;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import codechicken.multipart.asm.ASMMixinCompiler$;
import codechicken.multipart.asm.ASMMixinCompiler.ClassInfo;
import codechicken.multipart.asm.ASMMixinCompiler.MixinInfo;
import scala.collection.JavaConversions;
import scala.collection.mutable.Map;
class ASMMixinCompilerStartupFunctionalTest {
private static final ASMMixinCompiler$ COMPILER = ASMMixinCompiler$.MODULE$;
private static final String PREFIX = "codechicken/multipart/test/bootstrap/";
@Test
void bindsTheCompilerToItsActualForgeLaunchClassLoader() {
assertSame(ASMMixinCompiler$.class.getClassLoader(), COMPILER.cl());
assertInstanceOf(LaunchClassLoader.class, COMPILER.cl());
}
@Test
void resolvesAndOpensTheExactJdkAndLaunchWrapperMembers() {
Method define = COMPILER.m_defineClass();
assertEquals(ClassLoader.class, define.getDeclaringClass());
assertEquals("defineClass", define.getName());
assertArrayEquals(new Class<?>[] { byte[].class, int.class, int.class }, define.getParameterTypes());
assertEquals(Class.class, define.getReturnType());
assertTrue(Modifier.isFinal(define.getModifiers()));
assertTrue(define.isAccessible());
Method transform = COMPILER.m_runTransformers();
assertEquals(LaunchClassLoader.class, transform.getDeclaringClass());
assertEquals("runTransformers", transform.getName());
assertArrayEquals(new Class<?>[] { String.class, String.class, byte[].class }, transform.getParameterTypes());
assertEquals(byte[].class, transform.getReturnType());
assertTrue(Modifier.isPrivate(transform.getModifiers()));
assertTrue(transform.isAccessible());
Field exclusions = COMPILER.f_transformerExceptions();
assertEquals(LaunchClassLoader.class, exclusions.getDeclaringClass());
assertEquals("transformerExceptions", exclusions.getName());
assertEquals(Set.class, exclusions.getType());
assertTrue(Modifier.isPrivate(exclusions.getModifiers()));
assertTrue(exclusions.isAccessible());
}
@Test
void openedDefineMethodDefinesExecutableBytesOnAnIndependentLoader() throws Exception {
byte[] bytes = executable(PREFIX + "Defined", 73);
try (LaunchClassLoader loader = new LaunchClassLoader(new URL[0])) {
Class<?> defined = (Class<?>) COMPILER.m_defineClass().invoke(loader, bytes, 0, bytes.length);
assertSame(loader, defined.getClassLoader());
assertEquals(PREFIX.replace('/', '.') + "Defined", defined.getName());
assertEquals(73, defined.getMethod("value").invoke(null));
}
}
@Test
void openedTransformerMethodUsesTheReceiverLoaderAndPreservesBytesWithNoTransformers() throws Exception {
byte[] bytes = executable(PREFIX + "Transformed", 29);
try (LaunchClassLoader loader = new LaunchClassLoader(new URL[0])) {
byte[] transformed = (byte[]) COMPILER.m_runTransformers().invoke(
loader,
PREFIX.replace('/', '.') + "Transformed",
PREFIX.replace('/', '.') + "Transformed",
bytes);
assertSame(bytes, transformed);
assertEquals(PREFIX + "Transformed", new ClassReader(transformed).getClassName());
assertTrue(loader.getTransformers().isEmpty());
}
}
@Test
void openedTransformerExceptionFieldIsTheLiveSetUsedByTheCompilerLoader() throws Exception {
Field exclusions = COMPILER.f_transformerExceptions();
@SuppressWarnings("unchecked")
Set<String> value = (Set<String>) exclusions.get(COMPILER.cl());
Field direct = LaunchClassLoader.class.getDeclaredField("transformerExceptions");
direct.setAccessible(true);
assertSame(direct.get(COMPILER.cl()), value);
String marker = PREFIX.replace('/', '.') + "excluded";
boolean present = value.contains(marker);
try {
value.add(marker);
assertTrue(((Set<?>) direct.get(COMPILER.cl())).contains(marker));
} finally {
if (!present) value.remove(marker);
}
}
@Test
void startupMapStorageUsesIndependentMutableHashMaps() throws Exception {
Map<String, byte[]> bytes = map("traitByteMap");
Map<String, MixinInfo> mixins = map("mixinMap");
Map<String, ClassInfo> info = map("infoCache");
assertEquals("scala.collection.mutable.HashMap", bytes.getClass().getName());
assertEquals(bytes.getClass(), mixins.getClass());
assertEquals(bytes.getClass(), info.getClass());
assertNotSame(bytes, mixins);
assertNotSame(bytes, info);
assertNotSame(mixins, info);
java.util.Map<String, byte[]> oldBytes = new HashMap<>(JavaConversions.mapAsJavaMap(bytes));
java.util.Map<String, MixinInfo> oldMixins = new HashMap<>(JavaConversions.mapAsJavaMap(mixins));
java.util.Map<String, ClassInfo> oldInfo = new HashMap<>(JavaConversions.mapAsJavaMap(info));
try {
String key = PREFIX + "independent";
bytes.put(key, new byte[] { 1 });
assertFalse(mixins.contains(key));
assertFalse(info.contains(key));
mixins.put(key, null);
assertFalse(info.contains(key));
} finally {
bytes.clear();
oldBytes.forEach(bytes::put);
mixins.clear();
oldMixins.forEach(mixins::put);
info.clear();
oldInfo.forEach(info::put);
}
}
@Test
void sanityCheckerBytesAreAvailableThroughTheInitializedCompilerPath() throws Exception {
byte[] bytes = COMPILER.getBytes("cpw/mods/fml/common/asm/FMLSanityChecker");
assertNotNull(bytes);
ClassReader reader = new ClassReader(bytes);
assertEquals("cpw/mods/fml/common/asm/FMLSanityChecker", reader.getClassName());
assertEquals("java/lang/Object", reader.getSuperName());
assertTrue(reader.getItemCount() > 1);
}
private static byte[] executable(String name, int value) {
ClassWriter writer = new ClassWriter(0);
writer.visit(V1_6, ACC_PUBLIC, name, null, "java/lang/Object", null);
MethodVisitor method = writer.visitMethod(ACC_PUBLIC | ACC_STATIC, "value", "()I", null, null);
method.visitLdcInsn(value);
method.visitInsn(IRETURN);
method.visitMaxs(1, 0);
method.visitEnd();
writer.visitEnd();
return writer.toByteArray();
}
@SuppressWarnings("unchecked")
private static <T> Map<String, T> map(String name) throws Exception {
Field field = ASMMixinCompiler$.class.getDeclaredField(name);
field.setAccessible(true);
return (Map<String, T>) field.get(COMPILER);
}
}
@@ -0,0 +1,306 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.*;
import static org.objectweb.asm.Opcodes.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import codechicken.multipart.asm.ASMMixinCompiler;
import codechicken.multipart.asm.ASMMixinCompiler$;
import codechicken.multipart.asm.ASMMixinCompiler.ClassInfo;
import codechicken.multipart.asm.ASMMixinCompiler.MethodInfo;
import codechicken.multipart.asm.StackAnalyser;
import codechicken.multipart.asm.StackAnalyser.Const;
import codechicken.multipart.asm.StackAnalyser.Load;
import codechicken.multipart.asm.StackAnalyser.Param;
import codechicken.multipart.asm.StackAnalyser.StackEntry;
import codechicken.multipart.asm.StackAnalyser.Store;
import codechicken.multipart.asm.StackAnalyser.This;
import scala.Option;
import scala.Some;
import scala.collection.Iterable;
import scala.collection.mutable.Map;
class ASMSuperLookupFunctionalTest {
private static final Type OWNER = Type.getType(Child.class);
@Test
void rejectsOwnOwnerAndWrongNamesBeforeReadingTheDescriptorOrStack() {
StackAnalyser stack = stack("target");
stack.m().name = null;
assertFalse(ASMMixinCompiler.getSuper(call(OWNER.getInternalName(), null, null), stack).isDefined());
stack.m().name = "different";
assertFalse(ASMMixinCompiler.getSuper(call(null, "target", null), stack).isDefined());
assertFalse(ASMMixinCompiler.getSuper(call(null, null, null), stack).isDefined());
stack.m().name = "target";
assertThrows(NullPointerException.class, () -> ASMMixinCompiler.getSuper(call(null, "target", null), stack));
assertThrows(
IndexOutOfBoundsException.class,
() -> ASMMixinCompiler.getSuper(call(null, "target", "()I"), stack));
stack.m().name = null;
assertThrows(NullPointerException.class, () -> ASMMixinCompiler.getSuper(call(null, "target", "()I"), stack));
}
@Test
void stripsTheGreedyScalaSuperPrefixButRequiresACharacterBeforeIt() {
for (String name : new String[] { "target", "owner$$super$target", "first$$super$second$$super$target" }) {
MethodInfo result = lookup(name, "target", "()I").get();
assertEquals(Type.getInternalName(Parent.class), result.owner().name());
assertEquals("target", result.name());
}
assertFalse(lookup("$$super$target", "target", "()I").isDefined());
assertFalse(lookup("prefix$$super$targetSuffix", "target", "()I").isDefined());
assertFalse(lookup("target", "owner$$super$target", "()I").isDefined());
}
@Test
void startsAtTheAnalysedOwnersSuperclassAndSelectsTheExactConcreteNonPrivateSignature() {
assertEquals(Type.getInternalName(Parent.class), lookup("target", "target", "()I").get().owner().name());
StackAnalyser overload = stack("target");
overload.push(receiver());
overload.push(new Const(3, null));
MethodInfo result = ASMMixinCompiler.getSuper(call("unrelated/Owner", "target", "(I)I"), overload).get();
assertEquals(Type.getInternalName(Grandparent.class), result.owner().name());
assertEquals("(I)I", result.desc());
assertEquals(
Type.getInternalName(Grandparent.class),
lookup("inherited", "inherited", "()I").get().owner().name());
assertTrue(lookup("protectedTarget", "protectedTarget", "()I").isDefined());
assertFalse(lookup("hidden", "hidden", "()I").isDefined());
assertFalse(lookup("abstractTarget", "abstractTarget", "()I").isDefined());
assertFalse(lookup("childOnly", "childOnly", "()I").isDefined());
assertFalse(lookup("target", "target", "()J").isDefined());
StackAnalyser root = new StackAnalyser(Type.getType(Object.class), method("target"));
root.push(receiver());
assertFalse(ASMMixinCompiler.getSuper(call("unrelated/Owner", "target", "()I"), root).isDefined());
}
@Test
void requiresALoadOfThisButDoesNotValidateItsTypeTheInvocationOwnerOrOpcode() {
StackEntry[] rejected = { null, new Const(null, null), new Load(null, null),
new Load(new Param(0, OWNER), null), new Load(new Store(receiver(), null), null) };
for (StackEntry entry : rejected) {
StackAnalyser stack = stack("target");
stack.stack().$plus$eq(entry);
assertFalse(ASMMixinCompiler.getSuper(call("unrelated/Owner", "target", "()I"), stack).isDefined());
}
for (int opcode : new int[] { INVOKESPECIAL, INVOKEVIRTUAL, INVOKESTATIC, INVOKEINTERFACE }) {
StackAnalyser stack = stack("target");
// The pattern does not read This.owner or the entry's type.
stack.stack().$plus$eq(new Load(new This(null), null));
MethodInsnNode call = new MethodInsnNode(opcode, null, "target", "()I", opcode == INVOKEINTERFACE);
assertEquals(
Type.getInternalName(Parent.class),
ASMMixinCompiler$.MODULE$.getSuper(call, stack).get().owner().name());
assertEquals(1, stack.stack().size());
}
}
@Test
void retainsArgumentCountIndexingEvenWhenWideValuesOccupyTwoStackSlots() {
StackAnalyser narrow = stack("two");
Load receiver = receiver();
narrow.push(receiver);
narrow.push(new Const(1, null));
narrow.push(new Const(2, null));
assertTrue(ASMMixinCompiler.getSuper(call("parent", "two", "(II)I"), narrow).isDefined());
assertEquals(3, narrow.stack().size());
assertSame(receiver, narrow.peek(2));
for (Object value : new Object[] { 5L, 2.5D }) {
StackAnalyser wide = stack("wide");
wide.push(receiver);
Const argument = new Const(value, null);
wide.push(argument);
String desc = value instanceof Long ? "(J)I" : "(D)I";
assertSame(argument, wide.peek(1));
assertFalse(ASMMixinCompiler.getSuper(call("parent", "wide", desc), wide).isDefined());
assertEquals(3, wide.stack().size());
assertSame(receiver, wide.peek(2));
}
}
@Test
void preservesVirtualReadsAndUsesTheDescriptorAfterTheSuperclassCallback() throws Exception {
List<String> events = new ArrayList<>();
MethodInsnNode call = call("parent", "target", "()I");
Type switched = Type.getObjectType("codechicken/multipart/test/superlookup/Switched");
Option<MethodInfo> selected = new Some<>(lookup("target", "target", "()I").get());
ClassInfo parent = new TestInfo() {
@Override
public Option<MethodInfo> findPublicImpl(String name, String desc) {
events.add("find:" + name + desc);
return selected;
}
};
ClassInfo info = new TestInfo() {
@Override
public Option<ClassInfo> superClass() {
events.add("super:" + call.desc);
call.desc = "(J)I";
call.name = "changed";
return new Some<>(parent);
}
};
StackAnalyser stack = new StackAnalyser(OWNER, method("target")) {
private boolean switchedOwner;
@Override
public Type owner() {
events.add("owner:" + switchedOwner);
return switchedOwner ? switched : OWNER;
}
@Override
public StackEntry peek(int index) {
events.add("peek:" + index);
switchedOwner = true;
call.desc = "(I)I";
return new Load(new This(null), null) {
@Override
public codechicken.multipart.asm.StackAnalyser.LocalEntry e() {
events.add("load");
return super.e();
}
};
}
};
events.clear(); // Discard constructor reads; characterize only the query.
Map<String, ClassInfo> cache = cache();
Option<ClassInfo> previous = cache.put(switched.getInternalName(), info);
try {
assertSame(selected, ASMMixinCompiler.getSuper(call, stack));
assertEquals(
Arrays.asList("owner:false", "peek:0", "load", "owner:true", "super:(I)I", "find:target(J)I"),
events);
cache.put(switched.getInternalName(), new TestInfo() {
@Override
public Option<ClassInfo> superClass() {
return new Some<>(null);
}
});
call.name = "target";
assertThrows(NullPointerException.class, () -> ASMMixinCompiler.getSuper(call, stack));
} finally {
cache.remove(switched.getInternalName());
if (previous.isDefined()) cache.put(switched.getInternalName(), previous.get());
}
}
private static Option<MethodInfo> lookup(String methodName, String targetName, String desc) {
StackAnalyser stack = stack(methodName);
stack.push(receiver());
return ASMMixinCompiler.getSuper(call("unrelated/Owner", targetName, desc), stack);
}
private static StackAnalyser stack(String name) {
return new StackAnalyser(OWNER, method(name));
}
private static MethodNode method(String name) {
return new MethodNode(ACC_PUBLIC, name, "()I", null, null);
}
private static MethodInsnNode call(String owner, String name, String desc) {
return new MethodInsnNode(INVOKESPECIAL, owner, name, desc, false);
}
private static Load receiver() {
return new Load(new This(OWNER), null);
}
@SuppressWarnings("unchecked")
private static Map<String, ClassInfo> cache() throws Exception {
Field field = ASMMixinCompiler$.class.getDeclaredField("infoCache");
field.setAccessible(true);
return (Map<String, ClassInfo>) field.get(ASMMixinCompiler$.MODULE$);
}
private abstract static class TestInfo extends ClassInfo {
@Override
public String name() {
throw new AssertionError("Unexpected name read");
}
@Override
public Option<ClassInfo> superClass() {
throw new AssertionError("Unexpected superclass read");
}
@Override
public Iterable<ClassInfo> interfaces() {
throw new AssertionError("Unexpected interface read");
}
@Override
public Iterable<MethodInfo> methods() {
throw new AssertionError("Unexpected method read");
}
}
public static class Grandparent {
public int inherited() {
return 1;
}
public int target(int argument) {
return argument;
}
}
public abstract static class Parent extends Grandparent {
public int target() {
return 2;
}
protected int protectedTarget() {
return 3;
}
private int hidden() {
return 4;
}
public abstract int abstractTarget();
public int two(int first, int second) {
return first + second;
}
public int wide(long argument) {
return (int) argument;
}
public int wide(double argument) {
return (int) argument;
}
}
public abstract static class Child extends Parent {
@Override
public int target() {
return 5;
}
public int childOnly() {
return 6;
}
}
}
@@ -0,0 +1,190 @@
package codechicken.multipart.test;
import static codechicken.multipart.test.MixinClassesFunctionalTest.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.objectweb.asm.Opcodes.*;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import codechicken.lib.asm.ASMHelper;
import codechicken.multipart.asm.ASMMixinCompiler.MixinInfo;
class AbstractJavaMixinFunctionalTest {
private static final String ROOT = "codechicken/multipart/test/abstractmixin/";
@Test
void abstractLayerKeepsItsContractAndConcreteChildCompletesTheComposite() throws Exception {
try (Scope scope = new Scope()) {
ClassNode base = abstractIntBase("LayerBase");
Class<?> baseClass = scope.define(base);
ClassNode layer = abstractInput("Layer", base.name);
byte[] before = ASMHelper.createBytes(layer, 0);
COMPILER.registerJavaTrait(layer);
assertArrayEquals(before, ASMHelper.createBytes(layer, 0));
ClassNode contract = COMPILER.classNode(layer.name);
MethodNode required = method(contract, "required");
assertEquals(ACC_PUBLIC | ACC_ABSTRACT, required.access);
assertEquals(Arrays.asList("java/io/IOException"), required.exceptions);
ClassNode helper = COMPILER.classNode(layer.name + "$class");
assertFalse(helper.methods.stream().anyMatch(m -> ((MethodNode) m).name.equals("required")));
MixinInfo layerInfo = COMPILER.getMixinInfo(layer.name).get();
assertEquals(base.name, layerInfo.parent());
assertEquals(1, layerInfo.methods().size());
assertEquals("fromMixin", layerInfo.methods().apply(0).name);
ClassNode child = concreteInput("Child", layer.name);
COMPILER.registerJavaTrait(child);
MixinInfo childInfo = COMPILER.getMixinInfo(child.name).get();
assertEquals(base.name, childInfo.parent());
assertEquals(1, childInfo.parentTraits().size());
assertSame(layerInfo, childInfo.parentTraits().apply(0));
Class<?> composite = COMPILER.mixinClasses(ROOT + "LayerComposite", base.name, seq(child.name));
assertFalse(Modifier.isAbstract(composite.getModifiers()));
Object value = composite.getConstructor(int.class).newInstance(41);
assertEquals(41, composite.getField("seed").get(value));
assertEquals(23, composite.getMethod("required").invoke(value));
assertEquals(23, composite.getMethod("fromMixin").invoke(value));
assertEquals(23, baseClass.getMethod("fromBase").invoke(value));
String fieldName = layerInfo.fields().apply(0).accessName(layer.name);
assertEquals(11, composite.getMethod(fieldName).invoke(value));
}
}
@Test
void abstractConstructorsStillRejectParametersAndMissingDirectSuperCalls() throws Exception {
try (Scope scope = new Scope()) {
ClassNode arguments = node(ROOT + "Arguments", "java/lang/Object", ACC_PUBLIC | ACC_ABSTRACT);
arguments.visitMethod(ACC_PUBLIC, "<init>", "(I)V", null, null);
assertEquals(
"Constructor arguments are not permitted " + arguments.name + " as a mixin trait",
assertThrows(IllegalArgumentException.class, () -> COMPILER.registerJavaTrait(arguments))
.getMessage());
ClassNode invalid = node(ROOT + "Invalid", ROOT + "ExpectedBase", ACC_PUBLIC | ACC_ABSTRACT);
MethodVisitor constructor = invalid.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
constructor.visitVarInsn(ALOAD, 0);
constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
constructor.visitInsn(RETURN);
constructor.visitMaxs(1, 1);
IllegalArgumentException failure = assertThrows(
IllegalArgumentException.class,
() -> COMPILER.registerJavaTrait(invalid));
assertTrue(failure.getMessage().startsWith("Invalid constructor insn sequence " + invalid.name + "\n"));
for (ClassNode input : Arrays.asList(arguments, invalid)) {
assertFalse(scope.bytes.contains(input.name));
assertFalse(scope.bytes.contains(input.name + "$class"));
assertFalse(scope.mixins.contains(input.name));
}
}
}
@Test
void concreteMixinAlreadyTargetsAnAbstractBaseAndPreservesVirtualDispatch() throws Exception {
try (Scope scope = new Scope()) {
ClassNode base = abstractBase("Base");
Class<?> baseClass = scope.define(base);
ClassNode input = concreteInput("Concrete", base.name);
COMPILER.registerJavaTrait(input);
MixinInfo info = COMPILER.getMixinInfo(input.name).get();
assertEquals(base.name, info.parent());
assertEquals(2, info.methods().size());
Class<?> composite = COMPILER.mixinClasses(ROOT + "Composite", base.name, seq(input.name));
assertFalse(Modifier.isAbstract(composite.getModifiers()));
Object value = composite.getConstructor().newInstance();
assertEquals(23, composite.getMethod("required").invoke(value));
assertEquals(23, composite.getMethod("fromMixin").invoke(value));
assertEquals(23, baseClass.getMethod("fromBase").invoke(value));
}
}
private static ClassNode abstractBase(String suffix) {
ClassNode base = node(ROOT + suffix, "java/lang/Object", ACC_PUBLIC | ACC_ABSTRACT);
MethodVisitor constructor = base.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
constructor.visitVarInsn(ALOAD, 0);
constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
constructor.visitInsn(RETURN);
constructor.visitMaxs(1, 1);
base.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, "required", "()I", null, null);
MethodVisitor fromBase = base.visitMethod(ACC_PUBLIC, "fromBase", "()I", null, null);
fromBase.visitVarInsn(ALOAD, 0);
fromBase.visitMethodInsn(INVOKEVIRTUAL, base.name, "required", "()I", false);
fromBase.visitInsn(IRETURN);
fromBase.visitMaxs(1, 1);
return base;
}
private static ClassNode abstractIntBase(String suffix) {
ClassNode base = node(ROOT + suffix, "java/lang/Object", ACC_PUBLIC | ACC_ABSTRACT);
base.visitField(ACC_PUBLIC, "seed", "I", null, null);
MethodVisitor constructor = base.visitMethod(ACC_PUBLIC, "<init>", "(I)V", null, null);
constructor.visitVarInsn(ALOAD, 0);
constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
constructor.visitVarInsn(ALOAD, 0);
constructor.visitVarInsn(ILOAD, 1);
constructor.visitFieldInsn(PUTFIELD, base.name, "seed", "I");
constructor.visitInsn(RETURN);
constructor.visitMaxs(2, 2);
base.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, "required", "()I", null, null);
MethodVisitor fromBase = base.visitMethod(ACC_PUBLIC, "fromBase", "()I", null, null);
fromBase.visitVarInsn(ALOAD, 0);
fromBase.visitMethodInsn(INVOKEVIRTUAL, base.name, "required", "()I", false);
fromBase.visitInsn(IRETURN);
fromBase.visitMaxs(1, 1);
return base;
}
private static ClassNode abstractInput(String suffix, String parent) {
ClassNode input = node(ROOT + suffix, parent, ACC_PUBLIC | ACC_ABSTRACT);
input.visitField(ACC_PRIVATE, "initialized", "I", null, null);
MethodVisitor constructor = input.visitMethod(ACC_PROTECTED, "<init>", "()V", null, null);
constructor.visitVarInsn(ALOAD, 0);
constructor.visitInsn(ICONST_0);
constructor.visitMethodInsn(INVOKESPECIAL, parent, "<init>", "(I)V", false);
constructor.visitVarInsn(ALOAD, 0);
constructor.visitIntInsn(BIPUSH, 11);
constructor.visitFieldInsn(PUTFIELD, input.name, "initialized", "I");
constructor.visitInsn(RETURN);
constructor.visitMaxs(2, 1);
input.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, "required", "()I", null, new String[] { "java/io/IOException" });
MethodVisitor fromMixin = input.visitMethod(ACC_PUBLIC, "fromMixin", "()I", null, null);
fromMixin.visitVarInsn(ALOAD, 0);
fromMixin.visitMethodInsn(INVOKEVIRTUAL, input.name, "required", "()I", false);
fromMixin.visitInsn(IRETURN);
fromMixin.visitMaxs(1, 1);
return input;
}
private static ClassNode concreteInput(String suffix, String parent) {
ClassNode input = node(ROOT + suffix, parent, ACC_PUBLIC);
MethodVisitor constructor = input.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
constructor.visitVarInsn(ALOAD, 0);
constructor.visitMethodInsn(INVOKESPECIAL, parent, "<init>", "()V", false);
constructor.visitInsn(RETURN);
constructor.visitMaxs(1, 1);
MethodVisitor required = input.visitMethod(ACC_PUBLIC, "required", "()I", null, null);
required.visitIntInsn(BIPUSH, 23);
required.visitInsn(IRETURN);
required.visitMaxs(1, 1);
MethodVisitor fromMixin = input.visitMethod(ACC_PUBLIC, "fromMixin", "()I", null, null);
fromMixin.visitVarInsn(ALOAD, 0);
fromMixin.visitMethodInsn(INVOKEVIRTUAL, input.name, "required", "()I", false);
fromMixin.visitInsn(IRETURN);
fromMixin.visitMaxs(1, 1);
return input;
}
private static MethodNode method(ClassNode owner, String name) {
return (MethodNode) owner.methods.stream().filter(m -> ((MethodNode) m).name.equals(name)).findFirst().get();
}
}
@@ -0,0 +1,160 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.util.FakePlayerFactory;
import org.junit.jupiter.api.Test;
import codechicken.microblock.BlockMicroMaterial;
import codechicken.microblock.FaceMicroClass$;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.MicroMaterialRegistry.IMicroMaterial;
import codechicken.microblock.Microblock;
import codechicken.microblock.MissingMicroMaterial$;
import codechicken.multipart.TileMultipart;
import codechicken.multipart.examples.MaterialAccessExample;
import scala.Tuple2;
class BlockMicroMaterialFunctionalTest {
@Test
void typedQueryUsesFirstUsableBlockAndGuideNhMetadataFormatting() {
assertNull(MaterialAccessExample.resolvePrimaryMicroblockId(null));
assertNull(MaterialAccessExample.resolvePrimaryMicroblockId(new TileEntity()));
TileMultipart tile = new TileMultipart();
assertNull(MaterialAccessExample.resolvePrimaryMicroblockId(tile));
Microblock first = FaceMicroClass$.MODULE$.create(false, 0);
Microblock second = FaceMicroClass$.MODULE$.create(false, 1);
tile.setPartList(Arrays.asList(new MultipartGeneratorFunctionalTest.PlainPart(), first, second));
Tuple2<String, IMicroMaterial>[] materials = MicroMaterialRegistry.getIdMap();
Tuple2<String, IMicroMaterial> originalFirst = materials[0];
Tuple2<String, IMicroMaterial> originalSecond = materials[1];
try {
materials[1] = new Tuple2<>("test:second", new BlockMicroMaterial(Blocks.stone, 0));
for (int meta : new int[] { Integer.MIN_VALUE, -1, 0, 15, 17, Integer.MAX_VALUE }) {
materials[0] = new Tuple2<>("test:alias", new BlockMicroMaterial(Blocks.wool, meta));
assertEquals(
meta > 0 ? "minecraft:wool:" + meta : "minecraft:wool",
MaterialAccessExample.resolvePrimaryMicroblockId(tile));
}
for (IMicroMaterial skipped : new IMicroMaterial[] { MissingMicroMaterial$.MODULE$, null,
new BlockMicroMaterial(null, 0), new BlockMicroMaterial(Blocks.air, 0),
new BlockMicroMaterial(new Block(Material.rock) {}, 0) }) {
materials[0] = new Tuple2<>("test:skipped", skipped);
assertEquals("minecraft:stone", MaterialAccessExample.resolvePrimaryMicroblockId(tile));
}
materials[1] = materials[0];
assertNull(MaterialAccessExample.resolvePrimaryMicroblockId(tile));
} finally {
materials[0] = originalFirst;
materials[1] = originalSecond;
}
}
@Test
void typedQueryUsesVirtualAccessorsAndPropagatesFailuresWithoutSelectingALaterPart() {
Microblock first = FaceMicroClass$.MODULE$.create(false, 0);
Microblock second = FaceMicroClass$.MODULE$.create(false, 1);
TileMultipart tile = new TileMultipart();
tile.setPartList(Arrays.asList(first, second));
Tuple2<String, IMicroMaterial>[] materials = MicroMaterialRegistry.getIdMap();
Tuple2<String, IMicroMaterial> original = materials[0];
List<String> calls = new ArrayList<>();
RuntimeException failure = new IllegalStateException("material failure");
try {
materials[0] = new Tuple2<>("test:override", new BlockMicroMaterial(null, 3) {
@Override
public Block block() {
calls.add("block");
return Blocks.wool;
}
@Override
public int meta() {
calls.add("meta");
return 23;
}
});
assertEquals("minecraft:wool:23", MaterialAccessExample.resolvePrimaryMicroblockId(tile));
assertEquals(Arrays.asList("block", "meta"), calls);
materials[0] = new Tuple2<>("test:failure", new BlockMicroMaterial(null, 0) {
@Override
public int meta() {
throw failure;
}
});
assertSame(
failure,
assertThrows(RuntimeException.class, () -> MaterialAccessExample.resolvePrimaryMicroblockId(tile)));
first.material_$eq(Integer.MAX_VALUE);
assertThrows(IndexOutOfBoundsException.class, () -> MaterialAccessExample.resolvePrimaryMicroblockId(tile));
} finally {
materials[0] = original;
}
}
@Test
void registeredMaterialsExposeBlockAndMetadataWithoutClientInitialization() throws Exception {
int id = MicroMaterialRegistry.materialID("minecraft:stone");
BlockMicroMaterial material = (BlockMicroMaterial) MicroMaterialRegistry.getMaterial(id);
assertSame(MicroMaterialRegistry.getMaterial("minecraft:stone"), material);
assertSame(Blocks.stone, material.block());
assertEquals(0, material.meta());
assertSame(Blocks.wool, new BlockMicroMaterial(Blocks.wool, 23).block());
assertEquals(23, new BlockMicroMaterial(Blocks.wool, 23).meta());
assertEquals("minecraft:stone", net.minecraft.block.Block.blockRegistry.getNameForObject(material.block()));
}
@Test
void dedicatedServerKeepsCommonMaterialBehaviorAndStripsClientMembers() throws Exception {
BlockMicroMaterial material = (BlockMicroMaterial) MicroMaterialRegistry.getMaterial("minecraft:stone");
assertSame(Blocks.stone, material.block());
assertEquals(0, material.meta());
assertEquals("minecraft:stone", material.blockKey());
ItemStack item = material.getItem();
assertSame(Item.getItemFromBlock(Blocks.stone), item.getItem());
assertEquals(1, item.stackSize);
assertEquals(0, item.getItemDamage());
assertEquals(item.getDisplayName(), material.getLocalizedName());
assertFalse(material.isTransparent());
assertTrue(new BlockMicroMaterial(Blocks.glass, 0).isTransparent());
assertEquals(Blocks.glowstone.getLightValue(), new BlockMicroMaterial(Blocks.glowstone, 0).getLightValue());
assertEquals(Blocks.stone.getHarvestLevel(0), material.getCutterStrength());
assertSame(Blocks.stone.stepSound, material.getSound());
assertEquals(Blocks.stone.getExplosionResistance(null), material.explosionResistance(null));
WorldServer world = MinecraftServer.getServer().worldServers[0];
EntityPlayer player = FakePlayerFactory.getMinecraft(world);
float hardness = Blocks.stone.getBlockHardness(null, 0, 0, 0);
float expected = player.getBreakSpeed(Blocks.stone, false, 0, 0, -1, 0) / hardness;
assertEquals(expected, material.getStrength(player));
assertThrows(NoSuchFieldException.class, () -> BlockMicroMaterial.class.getDeclaredField("icont"));
assertThrows(NoSuchMethodException.class, () -> BlockMicroMaterial.class.getDeclaredMethod("loadIcons"));
assertThrows(
NoSuchMethodException.class,
() -> BlockMicroMaterial.class.getDeclaredMethod("getBreakingIcon", int.class));
assertSame(Blocks.stone, BlockMicroMaterial.class.getDeclaredMethod("block").invoke(material));
}
}
@@ -0,0 +1,146 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import net.minecraft.init.Blocks;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import org.junit.jupiter.api.Test;
import codechicken.lib.vec.BlockCoord;
import codechicken.multipart.examples.ButtonOrientationExample;
import codechicken.multipart.minecraft.ButtonPart;
class ButtonOrientationFunctionalTest {
private static final BlockCoord BUTTON = new BlockCoord(64, 200, 48);
@Test
void inverseLookupReadsLiveMappingsWithoutPlacementValidation() {
int[] originalMetaSideMap = ButtonPart.metaSideMap;
int[] originalSideMetaMap = ButtonPart.sideMetaMap;
try {
ButtonPart.metaSideMap = new int[] { -1, 4, 5, 2, 3, -1, -1, -1 };
ButtonPart.sideMetaMap = new int[] { -1, -1, 3, 4, 1, 2 };
for (int side = 0; side < 6; side++) {
assertEquals(ButtonPart.sideMetaMap[side], ButtonPart.metaForSide(side));
assertEquals(ButtonPart.sideMetaMap[side ^ 1], ButtonOrientationExample.metadataForClickedFace(side));
}
assertEquals(-1, ButtonPart.metaForSide(0));
ButtonPart.setOrientation(5, ForgeDirection.DOWN);
assertEquals(5, ButtonPart.metaForSide(0));
ButtonPart.setOrientation(5, ForgeDirection.UP);
assertEquals(-1, ButtonPart.metaForSide(0));
assertEquals(5, ButtonPart.metaForSide(1));
ButtonPart.sideMetaMap[2] = 7;
assertEquals(7, ButtonPart.metaForSide(2));
ButtonPart.sideMetaMap = new int[] { 5, 0, 3, 4, 1, 2 };
assertEquals(3, ButtonPart.metaForSide(2));
assertThrows(IndexOutOfBoundsException.class, () -> ButtonPart.metaForSide(-1));
assertThrows(IndexOutOfBoundsException.class, () -> ButtonPart.metaForSide(6));
} finally {
ButtonPart.metaSideMap = originalMetaSideMap;
ButtonPart.sideMetaMap = originalSideMetaMap;
}
}
@Test
void etFuturumArrayMutationEnablesFloorAndCeilingPlacement() {
World world = MinecraftServer.getServer().worldServers[0];
world.getChunkFromBlockCoords(BUTTON.x, BUTTON.z);
int[] originalMetaSideMap = ButtonPart.metaSideMap;
int[] originalSideMetaMap = ButtonPart.sideMetaMap;
int[] originalMetaSideValues = originalMetaSideMap.clone();
int[] originalSideMetaValues = originalSideMetaMap.clone();
try {
assertArrayEquals(new int[] { -1, 4, 5, 2, 3, -1, -1, -1 }, ButtonPart.metaSideMap);
assertArrayEquals(new int[] { -1, -1, 3, 4, 1, 2 }, ButtonPart.sideMetaMap);
prepareSupports(world);
assertNull(ButtonPart.placement(world, BUTTON, 0, 0));
assertNull(ButtonPart.placement(world, BUTTON, 1, 0));
int[] metaSideMap = ButtonPart.metaSideMap;
metaSideMap[0] = 1;
metaSideMap[5] = 0;
ButtonPart.metaSideMap = metaSideMap;
int[] sideMetaMap = ButtonPart.sideMetaMap;
sideMetaMap[0] = 5;
sideMetaMap[1] = 0;
ButtonPart.sideMetaMap = sideMetaMap;
assertSame(metaSideMap, ButtonPart.metaSideMap);
assertSame(sideMetaMap, ButtonPart.sideMetaMap);
assertArrayEquals(new int[] { 1, 4, 5, 2, 3, 0, -1, -1 }, ButtonPart.metaSideMap);
assertArrayEquals(new int[] { 5, 0, 3, 4, 1, 2 }, ButtonPart.sideMetaMap);
int[] expectedMetadata = { 0, 5, 4, 3, 2, 1 };
for (int side = 0; side < 6; side++) {
ButtonPart part = (ButtonPart) ButtonPart.placement(world, BUTTON, side, 0);
assertEquals(expectedMetadata[side], part.getMetadata());
assertEquals(side ^ 1, part.getFace());
}
} finally {
clear(world);
System.arraycopy(originalMetaSideValues, 0, originalMetaSideMap, 0, originalMetaSideMap.length);
System.arraycopy(originalSideMetaValues, 0, originalSideMetaMap, 0, originalSideMetaMap.length);
ButtonPart.metaSideMap = originalMetaSideMap;
ButtonPart.sideMetaMap = originalSideMetaMap;
}
}
@Test
void typedApiMatchesEtFuturumAndKeepsMappingsOneToOne() {
int[] originalMetaSideMap = ButtonPart.metaSideMap;
int[] originalSideMetaMap = ButtonPart.sideMetaMap;
int[] originalMetaSideValues = originalMetaSideMap.clone();
int[] originalSideMetaValues = originalSideMetaMap.clone();
try {
ButtonOrientationExample.registerVerticalOrientations();
assertArrayEquals(new int[] { 1, 4, 5, 2, 3, 0, -1, -1 }, ButtonPart.metaSideMap);
assertArrayEquals(new int[] { 5, 0, 3, 4, 1, 2 }, ButtonPart.sideMetaMap);
ButtonPart.setOrientation(1, ForgeDirection.DOWN);
assertArrayEquals(new int[] { 1, 0, 5, 2, 3, -1, -1, -1 }, ButtonPart.metaSideMap);
assertArrayEquals(new int[] { 1, 0, 3, 4, -1, 2 }, ButtonPart.sideMetaMap);
int[] metaSideValues = ButtonPart.metaSideMap.clone();
int[] sideMetaValues = ButtonPart.sideMetaMap.clone();
assertThrows(IllegalArgumentException.class, () -> ButtonPart.setOrientation(-1, ForgeDirection.UP));
assertThrows(IllegalArgumentException.class, () -> ButtonPart.setOrientation(8, ForgeDirection.UP));
assertThrows(IllegalArgumentException.class, () -> ButtonPart.setOrientation(0, null));
assertThrows(IllegalArgumentException.class, () -> ButtonPart.setOrientation(0, ForgeDirection.UNKNOWN));
assertArrayEquals(metaSideValues, ButtonPart.metaSideMap);
assertArrayEquals(sideMetaValues, ButtonPart.sideMetaMap);
} finally {
System.arraycopy(originalMetaSideValues, 0, originalMetaSideMap, 0, originalMetaSideMap.length);
System.arraycopy(originalSideMetaValues, 0, originalSideMetaMap, 0, originalSideMetaMap.length);
ButtonPart.metaSideMap = originalMetaSideMap;
ButtonPart.sideMetaMap = originalSideMetaMap;
}
}
private static void prepareSupports(World world) {
clear(world);
for (int side = 0; side < 6; side++) {
BlockCoord support = BUTTON.copy().offset(side);
assertTrue(world.setBlock(support.x, support.y, support.z, Blocks.stone, 0, 3));
}
}
private static void clear(World world) {
world.setBlockToAir(BUTTON.x, BUTTON.y, BUTTON.z);
for (int side = 0; side < 6; side++) {
BlockCoord support = BUTTON.copy().offset(side);
world.setBlockToAir(support.x, support.y, support.z);
}
}
}
@@ -0,0 +1,373 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.*;
import static org.objectweb.asm.Opcodes.*;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FrameNode;
import com.google.common.collect.HashBiMap;
import codechicken.lib.asm.ObfMapping;
import codechicken.multipart.asm.ASMMixinCompiler;
import codechicken.multipart.asm.ASMMixinCompiler$;
import codechicken.multipart.asm.ASMMixinCompiler.ClassInfo;
import codechicken.multipart.asm.DebugPrinter$;
import cpw.mods.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
import scala.collection.JavaConversions;
import scala.collection.mutable.Map;
class ClassBytesFunctionalTest {
private static final String NAME = "codechicken/multipart/test/bytes/Probe";
private static final String DOTTED = NAME.replace('/', '.');
@Test
void normalizesLoaderNamesAndRunsTheTransformerChainOnEveryDirectLookup() throws Exception {
try (State state = new State()) {
byte[] raw = { 1 }, middle = { 2 }, result = { 3 };
state.loader.bytes = raw;
state.bytes.put(NAME, new byte[] { 4 });
List<String> calls = new ArrayList<>();
state.transformers((name, transformed, input) -> {
calls.add(name + ":" + transformed);
assertSame(raw, input);
return middle;
}, (name, transformed, input) -> {
assertSame(middle, input);
return result;
});
assertSame(result, state.compiler.getBytes(NAME));
assertSame(result, ASMMixinCompiler.getBytes(DOTTED));
assertEquals(Arrays.asList(DOTTED, DOTTED), state.loader.names);
assertEquals(Arrays.asList(DOTTED + ":" + DOTTED, DOTTED + ":" + DOTTED), calls);
assertArrayEquals(new byte[] { 4 }, state.bytes.apply(NAME));
}
}
@Test
void objectAndMissingBytesSkipExclusionsAndNullNamesFailBeforeLoading() throws Exception {
try (State state = new State()) {
state.setExclusions(null);
assertNull(state.compiler.getBytes("java/lang/Object"));
assertNull(state.compiler.getBytes("java.lang.Object"));
assertThrows(NullPointerException.class, () -> state.compiler.getBytes(null));
assertTrue(state.loader.names.isEmpty());
assertNull(state.compiler.getBytes(NAME));
assertEquals(Arrays.asList(DOTTED), state.loader.names);
state.loader.bytes = new byte[] { 1 };
assertThrows(NullPointerException.class, () -> state.compiler.getBytes(NAME));
assertEquals(Arrays.asList(DOTTED, DOTTED), state.loader.names);
}
}
@Test
void exclusionsUseDottedPrefixesAndStopAtTheFirstMatch() throws Exception {
try (State state = new State()) {
state.loader.bytes = new byte[] { 1 };
state.transformers((name, transformed, bytes) -> {
fail("Excluded bytes must not reach transformers");
return bytes;
});
state.exclusions("unrelated", DOTTED.substring(0, DOTTED.length() - 1), null);
assertSame(state.loader.bytes, state.compiler.getBytes(NAME));
state.exclusions("", null);
assertSame(state.loader.bytes, state.compiler.getBytes(NAME));
state.exclusions(NAME, null);
assertThrows(NullPointerException.class, () -> state.compiler.getBytes(NAME));
}
}
@Test
void preservesNullTransformerResultsAndReflectiveExceptionWrapping() throws Exception {
try (State state = new State()) {
state.loader.bytes = new byte[] { 1 };
state.transformers((name, transformed, bytes) -> null);
assertNull(state.compiler.getBytes(NAME));
Error failure = new LinkageError("transformer probe");
state.transformers((name, transformed, bytes) -> { throw failure; });
InvocationTargetException thrown = assertThrows(
InvocationTargetException.class,
() -> state.compiler.getBytes(NAME));
assertSame(failure, thrown.getCause());
assertFalse(state.bytes.contains(NAME));
}
}
@Test
void remapsTheOriginalInputAndPassesDeobfuscatedThenObfuscatedNamesToTransformers() throws Exception {
try (State state = new State()) {
Field mappings = field(FMLDeobfuscatingRemapper.class, "classNameBiMap");
Object previous = mappings.get(FMLDeobfuscatingRemapper.INSTANCE);
Field obfuscated = writableStaticFinal(ObfMapping.class, "obfuscated");
boolean oldObfuscated = obfuscated.getBoolean(null);
HashBiMap<String, String> names = HashBiMap.create();
names.put("obf/Probe", NAME);
try {
mappings.set(FMLDeobfuscatingRemapper.INSTANCE, names);
obfuscated.setBoolean(null, true);
byte[] raw = { 1 }, result = { 2 };
state.loader.bytes = raw;
List<String> calls = new ArrayList<>();
state.transformers((name, transformed, bytes) -> {
assertSame(raw, bytes);
calls.add(name + ":" + transformed);
return result;
});
assertSame(result, state.compiler.getBytes(NAME));
assertSame(result, state.compiler.getBytes(DOTTED));
assertEquals(Arrays.asList("obf.Probe", DOTTED), state.loader.names);
assertEquals(Arrays.asList(DOTTED + ":obf.Probe", DOTTED + ":" + DOTTED), calls);
state.exclusions("obf.");
assertSame(result, state.compiler.getBytes(NAME));
state.exclusions(DOTTED);
assertSame(raw, state.compiler.getBytes(NAME));
assertEquals(3, calls.size());
} finally {
obfuscated.setBoolean(null, oldObfuscated);
mappings.set(FMLDeobfuscatingRemapper.INSTANCE, previous);
}
}
}
@Test
void classNodeCachesNormalizedRawBytesButReturnsFreshNodesWithExpandedFrames() throws Exception {
try (State state = new State()) {
byte[] bytes = definition(NAME);
state.loader.bytes = bytes;
ClassNode first = state.compiler.classNode(DOTTED);
assertEquals(NAME, first.name);
FrameNode frame = null;
for (AbstractInsnNode insn : first.methods.get(0).instructions.toArray()) {
if (insn instanceof FrameNode) frame = (FrameNode) insn;
}
assertNotNull(frame);
assertEquals(F_NEW, frame.type);
assertEquals(Arrays.asList(INTEGER), frame.local);
assertSame(bytes, state.bytes.apply(NAME));
assertFalse(state.bytes.contains(DOTTED));
first.methods.clear();
// Class version is read again from the retained array, rather than from a cached node or copied array.
bytes[7] = V1_8;
ClassNode second = ASMMixinCompiler.classNode(NAME);
assertNotSame(first, second);
assertEquals(1, second.methods.size());
assertEquals(V1_8, second.version);
assertEquals(Arrays.asList(DOTTED), state.loader.names);
}
}
@Test
void classNodeCachesNullResultsIncludingObjectAndDoesNotCacheNullNameFailures() throws Exception {
try (State state = new State()) {
assertNull(state.compiler.classNode(NAME));
assertTrue(state.bytes.get(NAME).isDefined());
assertNull(state.bytes.apply(NAME));
state.loader.bytes = definition(NAME);
assertNull(state.compiler.classNode(DOTTED));
assertEquals(1, state.loader.names.size());
state.bytes.remove("java/lang/Object");
assertNull(state.compiler.classNode("java.lang.Object"));
assertTrue(state.bytes.get("java/lang/Object").isDefined());
assertEquals(1, state.loader.names.size());
assertThrows(NullPointerException.class, () -> state.compiler.classNode(null));
assertFalse(state.bytes.contains(null));
}
}
@Test
void loadFailuresAreRetriedButParseFailuresKeepTheCachedBytes() throws Exception {
try (State state = new State()) {
IOException failure = new IOException("read probe");
state.loader.failure = failure;
assertSame(failure, assertThrows(IOException.class, () -> state.compiler.classNode(NAME)));
assertFalse(state.bytes.contains(NAME));
state.loader.failure = null;
byte[] malformed = new byte[0];
state.loader.bytes = malformed;
assertThrows(ArrayIndexOutOfBoundsException.class, () -> state.compiler.classNode(NAME));
assertSame(malformed, state.bytes.apply(NAME));
state.loader.bytes = definition(NAME);
assertThrows(ArrayIndexOutOfBoundsException.class, () -> state.compiler.classNode(DOTTED));
assertEquals(2, state.loader.names.size());
state.bytes.remove(NAME);
assertEquals(NAME, state.compiler.classNode(NAME).name);
assertEquals(3, state.loader.names.size());
}
}
@Test
void internalDefinePublishesTheSameArrayAndInvalidatesOnlyNormalizedMetadataWithoutDefiningAClass()
throws Exception {
try (State state = new State()) {
state.info.put(NAME, null);
state.info.put(DOTTED, null);
byte[] bytes = definition(NAME);
ASMMixinCompiler.internalDefine(DOTTED, bytes);
assertSame(bytes, state.bytes.apply(NAME));
assertFalse(state.info.contains(NAME));
assertTrue(state.info.contains(DOTTED));
assertEquals(NAME, state.compiler.classNode(DOTTED).name);
assertTrue(state.loader.names.isEmpty());
java.lang.reflect.Method loaded = ClassLoader.class.getDeclaredMethod("findLoadedClass", String.class);
loaded.setAccessible(true);
assertNull(loaded.invoke(state.loader, DOTTED));
}
}
@Test
void internalDefineKeepsCacheChangesWhenDumpingFailsAndAcceptsNullsWithDebugDisabled() throws Exception {
try (State state = new State()) {
DebugPrinter$ printer = DebugPrinter$.MODULE$;
Field debug = field(DebugPrinter$.class, "debug");
boolean oldDebug = debug.getBoolean(printer);
String name = NAME + "DumpFailure";
Path blockedDump = printer.dir().toPath().resolve(name.replace('/', '#') + ".txt");
Files.createDirectory(blockedDump);
try {
debug.setBoolean(printer, true);
state.info.put(name, null);
byte[] bytes = definition(name);
RuntimeException thrown = assertThrows(
RuntimeException.class,
() -> state.compiler.internalDefine(name, bytes));
assertInstanceOf(IOException.class, thrown.getCause());
assertSame(bytes, state.bytes.apply(name));
assertFalse(state.info.contains(name));
debug.setBoolean(printer, false);
state.info.put(null, null);
state.compiler.internalDefine(null, null);
assertTrue(state.bytes.get(null).isDefined());
assertNull(state.bytes.apply(null));
assertFalse(state.info.contains(null));
assertNull(state.compiler.classNode(null));
assertTrue(state.loader.names.isEmpty());
} finally {
debug.setBoolean(printer, oldDebug);
Files.delete(blockedDump);
}
}
}
private static byte[] definition(String name) {
ClassWriter writer = new ClassWriter(0);
writer.visit(V1_7, ACC_PUBLIC, name, null, "java/lang/Object", null);
MethodVisitor body = writer.visitMethod(ACC_PUBLIC | ACC_STATIC, "choose", "(Z)I", null, null);
body.visitCode();
body.visitVarInsn(ILOAD, 0);
Label other = new Label();
body.visitJumpInsn(IFEQ, other);
body.visitInsn(ICONST_1);
body.visitInsn(IRETURN);
body.visitLabel(other);
body.visitFrame(F_SAME, 0, null, 0, null);
body.visitInsn(ICONST_2);
body.visitInsn(IRETURN);
body.visitMaxs(1, 1);
body.visitEnd();
writer.visitEnd();
return writer.toByteArray();
}
private static Field field(Class<?> owner, String name) throws Exception {
Field field = owner.getDeclaredField(name);
field.setAccessible(true);
return field;
}
private static Field writableStaticFinal(Class<?> owner, String name) throws Exception {
// The Forge harness runs on Java 8. Temporarily switch the real environment flag to exercise remapping.
Field result = field(owner, name);
field(Field.class, "modifiers").setInt(result, result.getModifiers() & ~Modifier.FINAL);
return result;
}
private static class RecordingLoader extends LaunchClassLoader {
final List<String> names = new ArrayList<>();
byte[] bytes;
IOException failure;
RecordingLoader() {
super(new URL[0]);
}
@Override
public byte[] getClassBytes(String name) throws IOException {
names.add(name);
if (failure != null) throw failure;
return bytes;
}
}
/** Restores the singleton, loader and both cache contents even if a characterization assertion fails. */
private static class State implements AutoCloseable {
final ASMMixinCompiler$ compiler = ASMMixinCompiler$.MODULE$;
final Field loaderField = field(ASMMixinCompiler$.class, "cl");
final Object oldLoader = loaderField.get(compiler);
final RecordingLoader loader = new RecordingLoader();
final Map<String, byte[]> bytes = cache("traitByteMap");
final Map<String, ClassInfo> info = cache("infoCache");
final java.util.Map<String, byte[]> oldBytes = new HashMap<>(JavaConversions.mapAsJavaMap(bytes));
final java.util.Map<String, ClassInfo> oldInfo = new HashMap<>(JavaConversions.mapAsJavaMap(info));
State() throws Exception {
assertFalse(ObfMapping.obfuscated);
// Initialize the printer before substituting the loader.
assertNotNull(DebugPrinter$.MODULE$.dir());
exclusions();
bytes.remove(NAME);
bytes.remove(null);
loaderField.set(compiler, loader);
}
void exclusions(String... prefixes) throws Exception {
setExclusions(new LinkedHashSet<>(Arrays.asList(prefixes)));
}
void setExclusions(Object prefixes) throws Exception {
compiler.f_transformerExceptions().set(loader, prefixes);
}
void transformers(IClassTransformer... transformers) throws Exception {
field(LaunchClassLoader.class, "transformers").set(loader, Arrays.asList(transformers));
}
@SuppressWarnings("unchecked")
private <T> Map<String, T> cache(String name) throws Exception {
return (Map<String, T>) field(ASMMixinCompiler$.class, name).get(compiler);
}
@Override
public void close() throws Exception {
loaderField.set(compiler, oldLoader);
bytes.clear();
oldBytes.forEach(bytes::put);
info.clear();
oldInfo.forEach(info::put);
loader.close();
}
}
}
@@ -0,0 +1,359 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.*;
import static org.objectweb.asm.Opcodes.*;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import codechicken.multipart.asm.ASMMixinCompiler;
import codechicken.multipart.asm.ASMMixinCompiler$;
import codechicken.multipart.asm.ASMMixinCompiler.ClassInfo;
import codechicken.multipart.asm.DebugPrinter$;
import scala.collection.JavaConversions;
import scala.collection.mutable.Map;
class ClassDefinitionFunctionalTest {
private static final String NAME = "codechicken/multipart/test/definition/Probe";
private static final String MARKER = "forgemultipart.test.definition.initialized";
@Test
void publishesAndDumpsTheSuppliedKeyButDefinesTheBytecodeNameWithoutInitializingIt() throws Exception {
try (State state = new State()) {
String alias = NAME + "Alias", dotted = alias.replace('/', '.');
state.info.put(alias, null);
state.info.put(dotted, null);
state.debug.setBoolean(state.printer, true);
byte[] bytes = definition(NAME, 7, true);
Class<?> defined = ASMMixinCompiler.define(dotted, bytes);
assertEquals(NAME.replace('/', '.'), defined.getName());
assertSame(state.loader, defined.getClassLoader());
assertSame(defined, state.loader.loaded(defined.getName()));
assertSame(bytes, state.bytes.apply(alias));
assertFalse(state.bytes.contains(dotted));
assertFalse(state.info.contains(alias));
assertTrue(state.info.contains(dotted));
assertEquals(NAME, state.compiler.classNode(alias).name);
assertEquals(state.oldUsed + bytes.length, state.used());
assertNull(System.getProperty(MARKER));
String dump = new String(Files.readAllBytes(state.dump(alias)), java.nio.charset.StandardCharsets.UTF_8);
assertTrue(dump.contains(NAME));
assertEquals(7, defined.getMethod("value").invoke(null));
assertEquals("yes", System.getProperty(MARKER));
}
}
@Test
void duplicateDefinitionsStayReflectionWrappedAfterReplacingCachesAndCountingBytes() throws Exception {
try (State state = new State()) {
byte[] first = definition(NAME, 7, false), second = definition(NAME, 9, false);
Class<?> defined = state.compiler.define(NAME, first);
state.info.put(NAME, null);
InvocationTargetException thrown = assertThrows(
InvocationTargetException.class,
() -> state.compiler.define(NAME, second));
assertInstanceOf(LinkageError.class, thrown.getCause());
assertTrue(thrown.getCause().getMessage().contains("duplicate"));
assertSame(second, state.bytes.apply(NAME));
assertFalse(state.info.contains(NAME));
assertEquals(state.oldUsed + first.length + second.length, state.used());
assertSame(defined, state.loader.loaded(NAME.replace('/', '.')));
assertEquals(7, defined.getMethod("value").invoke(null));
}
}
@Test
void malformedBytesRemainPublishedAndCountedWhenTheJvmRejectsThem() throws Exception {
try (State state = new State()) {
byte[] malformed = { 1, 2, 3 };
state.info.put(NAME, null);
InvocationTargetException thrown = assertThrows(
InvocationTargetException.class,
() -> state.compiler.define(NAME, malformed));
assertInstanceOf(ClassFormatError.class, thrown.getCause());
assertSame(malformed, state.bytes.apply(NAME));
assertFalse(state.info.contains(NAME));
assertEquals(state.oldUsed + malformed.length, state.used());
assertNull(state.loader.loaded(NAME.replace('/', '.')));
}
}
@Test
void nullBytesArePublishedBeforeAccountingFails() throws Exception {
try (State state = new State()) {
state.info.put(NAME, null);
assertThrows(NullPointerException.class, () -> state.compiler.define(NAME, null));
assertTrue(state.bytes.get(NAME).isDefined());
assertNull(state.bytes.apply(NAME));
assertFalse(state.info.contains(NAME));
assertEquals(state.oldUsed, state.used());
assertNull(state.loader.loaded(NAME.replace('/', '.')));
}
}
@Test
void nullNamesAreAcceptedWithoutDumpsButFailBeforeAccountingWhenDumpsAreEnabled() throws Exception {
try (State state = new State()) {
byte[] bytes = definition(NAME, 7, false);
Class<?> defined = state.compiler.define(null, bytes);
assertEquals(NAME.replace('/', '.'), defined.getName());
assertSame(bytes, state.bytes.apply(null));
int counted = state.used();
state.debug.setBoolean(state.printer, true);
byte[] second = definition(NAME + "Other", 9, false);
state.info.put(null, null);
assertThrows(NullPointerException.class, () -> state.compiler.define(null, second));
assertSame(second, state.bytes.apply(null));
assertFalse(state.info.contains(null));
assertEquals(counted, state.used());
assertNull(state.loader.loaded((NAME + "Other").replace('/', '.')));
}
}
@Test
void failedDumpsKeepPublicationButPreventAccountingAndClassDefinition() throws Exception {
try (State state = new State()) {
Path blocked = state.dump(NAME);
Files.createDirectory(blocked);
try {
state.debug.setBoolean(state.printer, true);
state.info.put(NAME, null);
byte[] bytes = definition(NAME, 7, false);
RuntimeException thrown = assertThrows(
RuntimeException.class,
() -> state.compiler.define(NAME, bytes));
assertInstanceOf(IOException.class, thrown.getCause());
assertSame(bytes, state.bytes.apply(NAME));
assertFalse(state.info.contains(NAME));
assertEquals(state.oldUsed, state.used());
assertNull(state.loader.loaded(NAME.replace('/', '.')));
} finally {
Files.delete(blocked);
}
}
}
@Test
void accountingFailuresEscapeBeforeTheDuplicateErrorHandler() throws Exception {
try (State state = new State()) {
LinkageError failure = new LinkageError("duplicate accounting failure");
state.counter.setInt(state.printer, 15999);
state.logger.set(
state.printer,
Proxy.newProxyInstance(
Logger.class.getClassLoader(),
new Class<?>[] { Logger.class },
(proxy, method, args) -> {
assertEquals("debug", method.getName());
throw failure;
}));
byte[] bytes = definition(NAME, 7, false);
assertSame(failure, assertThrows(LinkageError.class, () -> state.compiler.define(NAME, bytes)));
assertSame(bytes, state.bytes.apply(NAME));
assertEquals(15999, state.used());
assertNull(state.loader.loaded(NAME.replace('/', '.')));
}
}
@Test
void inaccessibleReflectionFailsAfterPublicationAndAccounting() throws Exception {
try (State state = new State()) {
state.originalDefine.setAccessible(false);
byte[] bytes = definition(NAME, 7, false);
assertThrows(IllegalAccessException.class, () -> state.compiler.define(NAME, bytes));
assertSame(bytes, state.bytes.apply(NAME));
assertEquals(state.oldUsed + bytes.length, state.used());
assertNull(state.loader.loaded(NAME.replace('/', '.')));
}
}
@Test
void aDirectDuplicateLinkageErrorIsTranslatedWithTheOriginalRequestedNameAndCause() throws Exception {
try (State state = new State()) {
state.directFailure("prefix duplicate suffix");
byte[] bytes = definition(NAME, 7, false);
String dotted = NAME.replace('/', '.');
IllegalStateException thrown = assertThrows(
IllegalStateException.class,
() -> state.compiler.define(dotted, bytes));
assertEquals(
"class with name: " + dotted
+ " already loaded. Do not reference your java mixin classes before registering",
thrown.getMessage());
assertInstanceOf(LinkageError.class, thrown.getCause());
assertEquals("prefix duplicate suffix", thrown.getCause().getMessage());
assertSame(bytes, state.bytes.apply(NAME));
assertEquals(state.oldUsed + bytes.length, state.used());
}
}
@Test
void directNonmatchingLinkageErrorsEscapeAndNullMessagesKeepTheGuardFailure() throws Exception {
for (String message : new String[] { "other failure", "Duplicate", null }) {
try (State state = new State()) {
state.directFailure(message);
byte[] bytes = definition(NAME, 7, false);
if (message == null) {
assertThrows(NullPointerException.class, () -> state.compiler.define(NAME, bytes));
} else {
LinkageError thrown = assertThrows(LinkageError.class, () -> state.compiler.define(NAME, bytes));
assertEquals(message, thrown.getMessage());
}
assertSame(bytes, state.bytes.apply(NAME));
assertEquals(state.oldUsed + bytes.length, state.used());
}
}
}
private static byte[] definition(String name, int value, boolean initialize) {
ClassWriter writer = new ClassWriter(0);
writer.visit(V1_6, ACC_PUBLIC, name, null, "java/lang/Object", null);
if (initialize) {
MethodVisitor init = writer.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
init.visitCode();
init.visitLdcInsn(MARKER);
init.visitLdcInsn("yes");
init.visitMethodInsn(
INVOKESTATIC,
"java/lang/System",
"setProperty",
"(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;",
false);
init.visitInsn(POP);
init.visitInsn(RETURN);
init.visitMaxs(2, 0);
init.visitEnd();
}
MethodVisitor method = writer.visitMethod(ACC_PUBLIC | ACC_STATIC, "value", "()I", null, null);
method.visitCode();
method.visitIntInsn(BIPUSH, value);
method.visitInsn(IRETURN);
method.visitMaxs(1, 0);
method.visitEnd();
writer.visitEnd();
return writer.toByteArray();
}
private static Field field(Class<?> owner, String name) throws Exception {
Field field = owner.getDeclaredField(name);
field.setAccessible(true);
return field;
}
private static class DefinitionLoader extends LaunchClassLoader {
DefinitionLoader() {
super(new URL[0]);
}
Class<?> loaded(String name) {
return findLoadedClass(name);
}
Class<?> install(byte[] bytes) {
return defineClass(null, bytes, 0, bytes.length);
}
}
private static class State implements AutoCloseable {
final ASMMixinCompiler$ compiler = ASMMixinCompiler$.MODULE$;
final DebugPrinter$ printer = DebugPrinter$.MODULE$;
final Field cl = field(ASMMixinCompiler$.class, "cl");
final Object oldLoader = cl.get(compiler);
final DefinitionLoader loader = new DefinitionLoader();
final Field define = field(ASMMixinCompiler$.class, "m_defineClass");
final Method originalDefine = compiler.m_defineClass();
final boolean oldAccessible = originalDefine.isAccessible();
final Field debug = field(DebugPrinter$.class, "debug");
final boolean oldDebug = printer.debug();
final Field counter = field(DebugPrinter$.class, "permGenUsed");
final int oldUsed = used();
final Field logger = field(DebugPrinter$.class, "logger");
final Object oldLogger = printer.logger();
final Map<String, byte[]> bytes = cache("traitByteMap");
final Map<String, ClassInfo> info = cache("infoCache");
final java.util.Map<String, byte[]> oldBytes = new HashMap<>(JavaConversions.mapAsJavaMap(bytes));
final java.util.Map<String, ClassInfo> oldInfo = new HashMap<>(JavaConversions.mapAsJavaMap(info));
final String oldMarker = System.getProperty(MARKER);
State() throws Exception {
cl.set(compiler, loader);
debug.setBoolean(printer, false);
System.clearProperty(MARKER);
}
int used() throws Exception {
return counter.getInt(printer);
}
Path dump(String name) {
return printer.dir().toPath().resolve(name.replace('/', '#') + ".txt");
}
void directFailure(String message) throws Exception {
// Reflection wraps method-body failures but lets class-initialization LinkageErrors escape directly.
ClassWriter writer = new ClassWriter(0);
writer.visit(V1_6, ACC_PUBLIC, NAME + "ReflectionFailure", null, "java/lang/Object", null);
MethodVisitor init = writer.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
init.visitCode();
init.visitTypeInsn(NEW, "java/lang/LinkageError");
init.visitInsn(DUP);
if (message == null) init.visitInsn(ACONST_NULL);
else init.visitLdcInsn(message);
init.visitMethodInsn(INVOKESPECIAL, "java/lang/LinkageError", "<init>", "(Ljava/lang/String;)V", false);
init.visitInsn(ATHROW);
init.visitMaxs(3, 0);
init.visitEnd();
MethodVisitor method = writer
.visitMethod(ACC_PUBLIC | ACC_STATIC, "define", "([BII)Ljava/lang/Class;", null, null);
method.visitCode();
method.visitLdcInsn(Type.getType(Object.class));
method.visitInsn(ARETURN);
method.visitMaxs(1, 3);
method.visitEnd();
writer.visitEnd();
define.set(
compiler,
loader.install(writer.toByteArray()).getMethod("define", byte[].class, int.class, int.class));
}
@SuppressWarnings("unchecked")
private <T> Map<String, T> cache(String name) throws Exception {
return (Map<String, T>) field(ASMMixinCompiler$.class, name).get(compiler);
}
@Override
public void close() throws Exception {
cl.set(compiler, oldLoader);
define.set(compiler, originalDefine);
originalDefine.setAccessible(oldAccessible);
debug.setBoolean(printer, oldDebug);
counter.setInt(printer, oldUsed);
logger.set(printer, oldLogger);
bytes.clear();
oldBytes.forEach(bytes::put);
info.clear();
oldInfo.forEach(info::put);
if (oldMarker == null) System.clearProperty(MARKER);
else System.setProperty(MARKER, oldMarker);
loader.close();
}
}
}
@@ -0,0 +1,243 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.*;
import static org.objectweb.asm.Opcodes.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import codechicken.multipart.asm.ASMMixinCompiler;
import codechicken.multipart.asm.ASMMixinCompiler$;
import codechicken.multipart.asm.ASMMixinCompiler.ClassInfo;
import codechicken.multipart.asm.ASMMixinCompiler.ClassInfo$;
import codechicken.multipart.asm.ASMMixinCompiler.MethodInfo;
import scala.Option;
import scala.collection.Iterable;
import scala.collection.Iterator;
import scala.collection.mutable.Map;
class ClassInfoFunctionalTest {
@Test
void choosesJavaNodesAndReflectionFallbackWithTheirDistinctRootSemantics() throws Exception {
ASMMixinCompiler$ compiler = ASMMixinCompiler$.MODULE$;
ClassInfo object = compiler.getClassInfo(Object.class);
assertEquals(
"codechicken.multipart.asm.ASMMixinCompiler$ClassInfo$ReflectionClassInfo",
object.getClass().getName());
assertEquals("java/lang/Object", object.name());
assertFalse(object.superClass().isDefined());
assertTrue(object.interfaces().isEmpty());
assertEquals(Object.class.getMethods().length, object.methods().size());
ClassInfo child = compiler.getClassInfo(LoadedChild.class);
assertEquals("codechicken.multipart.asm.ASMMixinCompiler$ClassInfo$ClassNodeInfo", child.getClass().getName());
assertSame(compiler.getClassInfo(LoadedParent.class), child.superClass().get());
assertEquals(Arrays.asList("java/lang/Runnable", "java/lang/AutoCloseable"), names(child.interfaces()));
MethodInfo inherited = child.findPublicImpl("inherited", "()I").get();
assertSame(compiler.getClassInfo(LoadedParent.class), inherited.owner());
assertTrue(child.findPublicImpl("protectedMethod", "()V").isDefined());
assertFalse(child.findPublicImpl("privateMethod", "()V").isDefined());
assertFalse(child.findPublicImpl("run", "()V").isDefined());
ClassInfo reflected = construct("ReflectionClassInfo", Class.class, LoadedChild.class);
assertSame(child.superClass().get(), reflected.superClass().get());
assertEquals(names(child.interfaces()), names(reflected.interfaces()));
// Bytecode nodes preserve Some(null) for a null superclass; reflection represents the root as None.
ClassNode root = new ClassNode();
root.name = "test/Root";
Option<ClassInfo> superClass = construct("ClassNodeInfo", ClassNode.class, root).superClass();
assertTrue(superClass.isDefined());
assertNull(superClass.get());
compiler.remClassInfo((String) null);
}
@Test
void cachesExactStringKeysAndUsesOnlyTheNameOfSuppliedNodes() {
ASMMixinCompiler$ compiler = ASMMixinCompiler$.MODULE$;
String slash = Type.getInternalName(CacheSubject.class), dotted = CacheSubject.class.getName();
compiler.remClassInfo(slash);
compiler.remClassInfo(dotted);
try {
ClassInfo first = compiler.getClassInfo(slash);
assertSame(first, compiler.getClassInfo(CacheSubject.class));
assertSame(first, ASMMixinCompiler.getClassInfo(slash));
ClassNode misleading = new ClassNode();
misleading.name = slash;
misleading.superName = "test/Missing";
assertSame(first, compiler.getClassInfo(misleading));
assertTrue(first.methods().exists(new scala.runtime.AbstractFunction1<MethodInfo, Object>() {
@Override
public Object apply(MethodInfo method) {
return method.name().equals("actual");
}
}));
ClassInfo alias = compiler.getClassInfo(dotted);
assertNotSame(first, alias);
assertEquals(first.name(), alias.name());
assertSame(alias, compiler.getClassInfo(dotted));
assertSame(first, compiler.remClassInfo(slash).get());
assertFalse(compiler.remClassInfo(slash).isDefined());
assertNotSame(first, compiler.getClassInfo(slash));
assertSame(alias, compiler.getClassInfo(dotted));
} finally {
compiler.remClassInfo(slash);
compiler.remClassInfo(dotted);
}
}
@Test
void cachesNullResultsButDoesNotCacheFailuresOrTreatUncachedLookupsAsCached() throws Exception {
ASMMixinCompiler$ compiler = ASMMixinCompiler$.MODULE$;
Map<String, ClassInfo> cache = state("infoCache");
Option<ClassInfo> previousNull = cache.remove(null);
String missing = "codechicken/multipart/test/metadata/DefinitelyAbsent";
try {
assertNull(compiler.getClassInfo((Class<?>) null));
assertFalse(cache.contains(null));
assertThrows(NullPointerException.class, () -> compiler.getClassInfo((ClassNode) null));
assertNull(compiler.getClassInfo((String) null));
assertTrue(cache.contains(null));
assertTrue(compiler.remClassInfo((String) null).isDefined());
assertThrows(ClassNotFoundException.class, () -> compiler.getClassInfo(missing));
assertFalse(cache.contains(missing));
assertThrows(ClassNotFoundException.class, () -> compiler.getClassInfo(missing));
String name = Type.getInternalName(CacheSubject.class);
ClassInfo first = ClassInfo$.MODULE$.obtainInfo(name);
ClassInfo second = ClassInfo$.MODULE$.obtainInfo(name);
assertNotSame(first, second);
assertEquals(first.name(), second.name());
} finally {
cache.remove(null);
if (previousNull.isDefined()) cache.put(null, previousNull.get());
compiler.remClassInfo(missing);
}
}
@Test
void internalDefineInvalidatesOnlyTheNormalizedMetadataKey() throws Exception {
ASMMixinCompiler$ compiler = ASMMixinCompiler$.MODULE$;
String slash = "codechicken/multipart/test/metadata/CacheProbe", dotted = slash.replace('/', '.');
Map<String, byte[]> bytes = state("traitByteMap");
Map<String, ClassInfo> cache = state("infoCache");
Option<byte[]> oldBytes = bytes.get(slash);
Option<ClassInfo> oldSlash = cache.get(slash), oldDotted = cache.get(dotted);
try {
compiler.internalDefine(slash, definition(slash, "before"));
ClassInfo before = compiler.getClassInfo(slash);
ClassInfo alias = compiler.getClassInfo(dotted);
assertTrue(before.findPublicImpl("before", "()V").isDefined());
compiler.internalDefine(dotted, definition(slash, "after"));
ClassInfo after = compiler.getClassInfo(slash);
assertNotSame(before, after);
assertTrue(after.findPublicImpl("after", "()V").isDefined());
assertFalse(after.findPublicImpl("before", "()V").isDefined());
assertSame(alias, compiler.getClassInfo(dotted));
assertTrue(alias.findPublicImpl("before", "()V").isDefined());
assertEquals("after", compiler.classNode(slash).methods.get(0).name);
} finally {
restore(bytes, slash, oldBytes);
restore(cache, slash, oldSlash);
restore(cache, dotted, oldDotted);
}
}
@Test
void readsScalaTraitAndCompanionMetadataFromTheRetainedSignatures() throws Exception {
ASMMixinCompiler$ compiler = ASMMixinCompiler$.MODULE$;
String traitName = "codechicken/multipart/test/ExternalScalaMicroblockFixture";
ClassInfo trait = compiler.getClassInfo(traitName);
assertEquals("codechicken.multipart.asm.ASMMixinCompiler$ClassInfo$ScalaClassInfo", trait.getClass().getName());
assertTrue(trait.isScala());
assertTrue(trait.isTrait());
assertFalse(trait.isObject());
assertEquals("codechicken/microblock/Microblock", trait.superClass().get().name());
codechicken.multipart.asm.ScalaSignature signature = (codechicken.multipart.asm.ScalaSignature) trait.getClass()
.getMethod("sig").invoke(trait);
assertTrue(signature.findClass(traitName.replace('/', '.')).isDefined());
assertSame(
trait.getClass().getMethod("csym").invoke(trait).getClass(),
signature.findClass(traitName.replace('/', '.')).get().getClass());
assertEquals(traitName, trait.moduleName());
String module = "codechicken/multipart/asm/StackAnalyser$";
ClassInfo info = compiler.getClassInfo(module);
assertEquals("codechicken.multipart.asm.ASMMixinCompiler$ClassInfo$ScalaClassInfo", info.getClass().getName());
assertTrue(info.isScala());
assertTrue(info.isObject());
assertFalse(info.isTrait());
// The companion is resolved from the base class's signature and bytecode node.
assertEquals(module.substring(0, module.length() - 1), info.name());
assertEquals(info.name(), info.moduleName());
// The current decoder cannot interpret this object's TypeRefType as a ClassType.
assertThrows(ClassCastException.class, info::superClass);
assertThrows(ClassCastException.class, info::interfaces);
assertTrue(
((codechicken.multipart.asm.ScalaSignature.ClassSymbolRef) info.getClass().getMethod("csym")
.invoke(info)).isObject());
}
private static ClassInfo construct(String nestedName, Class<?> parameter, Object value) throws Exception {
return (ClassInfo) Class.forName("codechicken.multipart.asm.ASMMixinCompiler$ClassInfo$" + nestedName)
.getConstructor(parameter).newInstance(value);
}
private static List<String> names(Iterable<ClassInfo> infos) {
List<String> result = new ArrayList<>();
Iterator<ClassInfo> iterator = infos.iterator();
while (iterator.hasNext()) result.add(iterator.next().name());
return result;
}
private static byte[] definition(String name, String method) {
ClassWriter writer = new ClassWriter(0);
writer.visit(V1_6, ACC_PUBLIC, name, null, "java/lang/Object", null);
org.objectweb.asm.MethodVisitor body = writer.visitMethod(ACC_PUBLIC, method, "()V", null, null);
body.visitCode();
body.visitInsn(RETURN);
body.visitMaxs(0, 1);
body.visitEnd();
writer.visitEnd();
return writer.toByteArray();
}
@SuppressWarnings("unchecked")
private static <T> Map<String, T> state(String name) throws Exception {
Field field = ASMMixinCompiler$.class.getDeclaredField(name);
field.setAccessible(true);
return (Map<String, T>) field.get(ASMMixinCompiler$.MODULE$);
}
private static <T> void restore(Map<String, T> map, String key, Option<T> old) {
map.remove(key);
if (old.isDefined()) map.put(key, old.get());
}
public static class LoadedParent {
public int inherited() {
return 3;
}
protected void protectedMethod() {}
private void privateMethod() {}
}
public abstract static class LoadedChild extends LoadedParent implements Runnable, AutoCloseable {
}
public static class CacheSubject {
public void actual() {}
}
}
@@ -0,0 +1,182 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicInteger;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import org.junit.jupiter.api.Test;
import codechicken.lib.vec.BlockCoord;
import codechicken.multipart.MultipartGenerator;
import codechicken.multipart.MultipartGenerator$;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TileMultipart;
import codechicken.multipart.TileMultipartClient;
import codechicken.multipart.examples.CompositeGenerationExample;
import codechicken.multipart.scalatraits.TSlottedTile;
import scala.collection.JavaConversions;
class CompositeGenerationFunctionalTest {
@Test
void javaGenerationSelectsCapabilitiesWithoutLoadingOrCopyingTiles() {
checkStaging(MultipartGenerator::generateCompositeTile);
}
@Test
void javaGenerationReadsInputOnceAndPropagatesFailuresBeforeReuse() {
checkInput(MultipartGenerator::generateCompositeTile);
}
@Test
void javaExactReflectionAcceptsJavaParts() throws Exception {
Method method = MultipartGenerator.class
.getMethod("generateCompositeTile", TileEntity.class, Iterable.class, boolean.class);
TileMultipart tile = (TileMultipart) method.invoke(null, null, Collections.emptyList(), true);
assertTrue(tile instanceof TileMultipartClient);
assertSame(tile, method.invoke(null, tile, Collections.emptyList(), true));
assertNull(tile.getWorldObj());
assertTrue(tile.jPartList().isEmpty());
}
@Test
void javaExamplePreparesWorldAndCoordinatesBeforeLoadingWithoutInstallation() {
for (boolean client : new boolean[] { false, true }) {
World world = client ? null : MinecraftServer.getServer().worldServers[0];
BlockCoord pos = new BlockCoord(78, 200, 48);
TileEntity installed = world == null ? null : world.getTileEntity(pos.x, pos.y, pos.z);
TMultiPart part = new MultipartGeneratorFunctionalTest.SlottedPart();
List<TMultiPart> parts = Collections.singletonList(part);
TileMultipart tile = CompositeGenerationExample.createUninstalledTile(world, pos, parts, client);
assertEquals(client, tile instanceof TileMultipartClient);
assertSame(world, tile.getWorldObj());
assertEquals(pos, new BlockCoord(tile));
assertSame(tile, part.tile());
assertSame(part, tile.partMap(3));
assertEquals(parts, tile.jPartList());
if (world != null) assertSame(installed, world.getTileEntity(pos.x, pos.y, pos.z));
}
}
@Test
void legacyGenerationSelectsCapabilitiesWithoutLoadingOrCopyingTiles() {
checkStaging(CompositeGenerationFunctionalTest::legacyGenerate);
}
@Test
void legacyGenerationReadsInputOnceAndPropagatesFailuresBeforeReuse() {
checkInput(CompositeGenerationFunctionalTest::legacyGenerate);
}
@Test
void legacyExactReflectionAndScalaArgumentsKeepTheCompanionPath() throws Exception {
Object parts = JavaConversions.asScalaBuffer(Collections.<TMultiPart>emptyList()).toList();
Method legacy = MultipartGenerator$.class
.getMethod("generateCompositeTile", TileEntity.class, scala.collection.Iterable.class, boolean.class);
TileMultipart tile = (TileMultipart) legacy.invoke(MultipartGenerator$.MODULE$, null, parts, true);
assertTrue(tile instanceof TileMultipartClient);
// GuideNH selects by argument assignability before falling back to the companion.
for (Method method : MultipartGenerator.class.getMethods()) {
if (method.getName().equals("generateCompositeTile") && method.getParameterCount() == 3) {
assertFalse(method.getParameterTypes()[1].isInstance(parts));
}
}
}
private static TileMultipart legacyGenerate(TileEntity tile, Iterable<TMultiPart> parts, boolean client) {
return MultipartGenerator$.MODULE$
.generateCompositeTile(tile, JavaConversions.iterableAsScalaIterable(parts), client);
}
private static void checkStaging(Generator generate) {
for (boolean client : new boolean[] { false, true }) {
TMultiPart part = new MultipartGeneratorFunctionalTest.SlottedPart();
List<TMultiPart> parts = Collections.singletonList(part);
TileMultipart source = generate.apply(null, parts, client);
assertEquals(client, source instanceof TileMultipartClient);
assertTrue(source instanceof TSlottedTile);
assertTrue(source.jPartList().isEmpty());
assertNull(source.partMap(3));
assertNull(part.tile());
source.loadPartList(parts);
source.xCoord = 78;
source.yCoord = 200;
source.zCoord = 48;
source.setWorldObj(MinecraftServer.getServer().worldServers[0]);
assertSame(source, generate.apply(source, parts, client));
assertSame(source, generate.apply(source, Arrays.asList(part, part), client));
assertEquals(parts, source.jPartList());
assertSame(part, source.partMap(3));
assertSame(source, part.tile());
TileMultipart replacement = generate.apply(source, parts, !client);
assertNotSame(source, replacement);
assertEquals(!client, replacement instanceof TileMultipartClient);
assertTrue(replacement instanceof TSlottedTile);
assertTrue(replacement.jPartList().isEmpty());
assertNull(replacement.partMap(3));
assertNull(replacement.getWorldObj());
assertEquals(0, replacement.xCoord);
assertEquals(0, replacement.yCoord);
assertEquals(0, replacement.zCoord);
assertFalse(source.isInvalid());
assertSame(source, part.tile());
assertEquals(parts, source.jPartList());
TileMultipart empty = generate.apply(source, Collections.emptyList(), client);
assertNotSame(source, empty);
assertFalse(empty instanceof TSlottedTile);
assertTrue(empty.jPartList().isEmpty());
assertSame(empty, generate.apply(empty, Collections.emptyList(), client));
assertSame(empty.getClass(), generate.apply(new TileEntity(), Collections.emptyList(), client).getClass());
replacement.loadPartList(parts);
assertSame(replacement, part.tile());
assertSame(part, replacement.partMap(3));
assertEquals(parts, source.jPartList(), "Loading the replacement does not clear the old tile");
}
}
private static void checkInput(Generator generate) {
List<TMultiPart> parts = Collections.singletonList(new MultipartGeneratorFunctionalTest.SlottedPart());
AtomicInteger iterations = new AtomicInteger();
Iterable<TMultiPart> counted = () -> {
iterations.incrementAndGet();
return parts.iterator();
};
TileMultipart tile = generate.apply(null, counted, false);
assertEquals(1, iterations.get());
assertSame(tile, generate.apply(tile, counted, false));
assertEquals(2, iterations.get(), "Even tile reuse evaluates the supplied parts");
IllegalStateException failure = new IllegalStateException("input failed");
Iterable<TMultiPart> broken = () -> { throw failure; };
assertSame(failure, assertThrows(IllegalStateException.class, () -> generate.apply(tile, broken, false)));
assertThrows(NullPointerException.class, () -> generate.apply(tile, null, false));
assertThrows(NullPointerException.class, () -> generate.apply(tile, Collections.singletonList(null), false));
int before = iterations.get();
assertThrows(
NoSuchElementException.class,
() -> generate.apply(new MultipartGeneratorFunctionalTest.UnregisteredTile(), counted, false));
assertEquals(before + 1, iterations.get(), "Parts are read before an unregistered tile class is rejected");
assertTrue(tile.jPartList().isEmpty());
}
private interface Generator {
TileMultipart apply(TileEntity tile, Iterable<TMultiPart> parts, boolean client);
}
}
@@ -0,0 +1,101 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.UUID;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.FakePlayerFactory;
import net.minecraftforge.event.entity.player.PlayerEvent.Clone;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.mojang.authlib.GameProfile;
import codechicken.multipart.ControlKeyModifer;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedOutEvent;
/**
* isControlDown needs a player with a world to pick its branch. On a dedicated server the world is never remote, so
* these cover the server half: the map the client keeps in sync through packet 1. The client half reads
* isClientPressing instead and no test harness has a client.
*/
class ControlKeyModiferFunctionalTest {
@Test
void replacementAndLogoutReleaseOldPlayerReferences() {
EntityPlayer original = player();
EntityPlayer replacement = FakePlayerFactory.get(
(WorldServer) original.worldObj,
new GameProfile(UUID.fromString("5f09d0b1-0aa8-4bc2-a362-5dd96d81eb55"), "modifier-test"));
record(original, true);
MinecraftForge.EVENT_BUS.post(new Clone(replacement, original, true));
assertFalse(ControlKeyModifer.map().containsKey(original));
assertTrue(ControlKeyModifer.isControlDown(replacement));
FMLCommonHandler.instance().bus().post(new PlayerLoggedOutEvent(replacement));
assertFalse(ControlKeyModifer.map().containsKey(replacement));
assertFalse(ControlKeyModifer.isControlDown(replacement));
}
@BeforeEach
@AfterEach
void clearRecordedPlayers() {
clearAll();
}
@Test
void aPlayerTheServerHasNotHeardFromIsNotHoldingTheKey() {
assertFalse(ControlKeyModifer.isControlDown(player()));
}
@Test
void reflectsWhatTheServerLastRecordedForThePlayer() {
EntityPlayer player = player();
record(player, true);
assertTrue(ControlKeyModifer.isControlDown(player));
record(player, false);
assertFalse(ControlKeyModifer.isControlDown(player));
}
/** Server stop clears the map, so a player must not carry a held key into the next run. */
@Test
void clearingResetsThePlayerToNotHolding() {
EntityPlayer player = player();
record(player, true);
clearAll();
assertFalse(ControlKeyModifer.isControlDown(player));
}
// The two adapters below are the only places the map's collection type is named.
private static void record(EntityPlayer player, boolean pressed) {
ControlKeyModifer.map().put(player, pressed);
}
private static void clearAll() {
ControlKeyModifer.map().clear();
}
private static EntityPlayer player() {
WorldServer world = MinecraftServer.getServer().worldServers[0];
assertNotNull(world);
EntityPlayer player = FakePlayerFactory.getMinecraft(world);
assertNotNull(player);
assertFalse(player.worldObj.isRemote, "A dedicated server world is never remote");
return player;
}
}
@@ -0,0 +1,128 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.*;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
import net.minecraft.nbt.NBTTagCompound;
import org.junit.jupiter.api.Test;
import codechicken.lib.data.MCDataInput;
import codechicken.lib.data.MCDataOutputWrapper;
import codechicken.lib.vec.Cuboid6;
import codechicken.microblock.CornerMicroClass;
import codechicken.microblock.CornerMicroClass$;
import codechicken.microblock.CornerMicroblock;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.Microblock;
import codechicken.microblock.MicroblockGenerator;
class CornerMicroblockTraitsFunctionalTest {
@Test
void generatedCornerKeepsClassIdentityAndAllFiftySixBounds() {
Microblock part = MicroblockGenerator.create(CornerMicroClass$.MODULE$, 0, false);
CornerMicroblock cornerPart = (CornerMicroblock) part;
assertSame(CornerMicroClass$.MODULE$, cornerPart.microClass());
assertSame(CornerMicroClass$.MODULE$, part.microClass());
assertEquals("mcr_cnr", part.getType());
int[] axisBits = { 4, 1, 2 };
for (int size = 1; size <= 7; size++) {
for (int corner = 0; corner < 8; corner++) {
part.setShape(size, corner + 7);
assertEquals(size, part.getSize());
assertEquals(corner + 7, cornerPart.getSlot());
assertEquals(1 << (corner + 7), cornerPart.getSlotMask());
Cuboid6 bounds = cornerPart.getBounds();
assertSame(CornerMicroClass.aBounds()[size * 16 + corner], bounds);
double distance = size / 8D;
double[] min = { bounds.min.x, bounds.min.y, bounds.min.z };
double[] max = { bounds.max.x, bounds.max.y, bounds.max.z };
for (int axis = 0; axis < 3; axis++) {
boolean positive = (corner & axisBits[axis]) != 0;
assertEquals(positive ? 1 - distance : 0, min[axis], 1e-12);
assertEquals(positive ? 1 : distance, max[axis], 1e-12);
}
}
}
}
@Test
void boundsUseSignedShapeIndexAndTheLiveReplaceableArray() {
Microblock part = MicroblockGenerator.create(CornerMicroClass$.MODULE$, 0, false);
CornerMicroblock corner = (CornerMicroblock) part;
for (int shape : new int[] { 0, 8, 127 }) {
part.shape_$eq((byte) shape);
assertNull(corner.getBounds());
}
for (int shape = -128; shape < 0; shape++) {
part.shape_$eq((byte) shape);
assertThrows(ArrayIndexOutOfBoundsException.class, corner::getBounds);
}
Cuboid6[] original = CornerMicroClass.aBounds();
Cuboid6[] replacement = new Cuboid6[256];
Cuboid6 sentinel = new Cuboid6(0.1, 0.2, 0.3, 0.4, 0.5, 0.6);
replacement[35] = sentinel;
part.setShape(2, 10);
try {
CornerMicroClass.aBounds_$eq(replacement);
assertSame(sentinel, corner.getBounds());
replacement[35] = null;
assertNull(corner.getBounds());
CornerMicroClass.aBounds_$eq(new Cuboid6[1]);
assertThrows(ArrayIndexOutOfBoundsException.class, corner::getBounds);
} finally {
CornerMicroClass.aBounds_$eq(original);
}
assertSame(original[35], corner.getBounds());
}
@Test
void generatedCornersKeepThePackedShapeInNbtAndDescriptions() {
Microblock part = MicroblockGenerator.create(CornerMicroClass$.MODULE$, 0, false);
Microblock loaded = MicroblockGenerator.create(CornerMicroClass$.MODULE$, 0, false);
ByteArrayOutputStream prefixBytes = new ByteArrayOutputStream();
MicroMaterialRegistry.writeMaterialID(new MCDataOutputWrapper(new DataOutputStream(prefixBytes)), 0);
byte[] prefix = prefixBytes.toByteArray();
for (int size : new int[] { 1, 4, 7 }) {
for (int corner = 0; corner < 8; corner++) {
byte shape = (byte) (size * 16 + corner);
part.setShape(size, corner + 7);
NBTTagCompound tag = new NBTTagCompound();
part.save(tag);
assertEquals(shape, tag.getByte("shape"));
assertEquals(MicroMaterialRegistry.materialName(0), tag.getString("material"));
loaded.load(tag);
assertEquals(shape, loaded.shape());
assertEquals(0, loaded.material());
assertEquals(corner + 7, ((CornerMicroblock) loaded).getSlot());
assertSame(part.getBounds(), loaded.getBounds());
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
part.writeDesc(new MCDataOutputWrapper(new DataOutputStream(bytes)));
byte[] expected = Arrays.copyOf(prefix, prefix.length + 1);
expected[prefix.length] = shape;
assertArrayEquals(expected, bytes.toByteArray());
AtomicInteger reads = new AtomicInteger();
MCDataInput input = (MCDataInput) Proxy.newProxyInstance(
getClass().getClassLoader(),
new Class<?>[] { MCDataInput.class },
(proxy, method, args) -> {
assertEquals("readByte", method.getName());
reads.incrementAndGet();
return shape;
});
loaded.setShape(2, 7);
loaded.readDesc(input);
assertEquals(1, reads.get());
assertEquals(shape, loaded.shape());
assertEquals(corner + 7, ((CornerMicroblock) loaded).getSlot());
}
}
}
}
@@ -0,0 +1,76 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
import codechicken.multipart.MultipartGenerator;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TileMultipart;
import codechicken.multipart.TileMultipartClient;
import codechicken.multipart.examples.CustomTileTraitCapability;
import codechicken.multipart.examples.CustomTileTraitExample;
import codechicken.multipart.examples.CustomTileTraitPart;
class CustomTileTraitFunctionalTest {
@Test
void registeredJavaTraitIsSelectedOnBothSidesAndExposesItsStableCapability() {
for (boolean client : new boolean[] { false, true }) {
ContributingPart first = new ContributingPart(4);
ContributingPart second = new ContributingPart(7);
List<TMultiPart> parts = Arrays.asList(first, new PlainPart(), second);
TileMultipart tile = MultipartGenerator.generateCompositeTile(null, parts, client);
assertEquals(client, tile instanceof TileMultipartClient);
assertTrue(tile instanceof CustomTileTraitCapability);
assertEquals(0, CustomTileTraitExample.totalContribution(tile), "Generation does not load parts");
tile.loadPartList(parts);
assertEquals(11, CustomTileTraitExample.totalContribution(tile));
assertEquals(1, first.calls);
assertEquals(1, second.calls);
assertSame(tile, first.tile());
assertSame(tile, second.tile());
assertSame(tile, MultipartGenerator.generateCompositeTile(tile, parts, client));
assertSame(
tile.getClass(),
MultipartGenerator.generateCompositeTile(null, Arrays.asList(new ContributingPart(1)), client)
.getClass());
}
assertFalse(new TileMultipart() instanceof CustomTileTraitCapability);
assertEquals(0, CustomTileTraitExample.totalContribution(new TileMultipart()));
assertEquals(0, CustomTileTraitExample.totalContribution(null));
}
private static class PlainPart extends TMultiPart {
@Override
public String getType() {
return "custom_tile_trait:plain";
}
}
private static final class ContributingPart extends PlainPart implements CustomTileTraitPart {
private final int contribution;
private int calls;
private ContributingPart(int contribution) {
this.contribution = contribution;
}
@Override
public int tileContribution() {
calls++;
return contribution;
}
}
}
@@ -0,0 +1,192 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodNode;
import codechicken.lib.asm.ASMHelper;
import codechicken.lib.config.ConfigTag;
import codechicken.multipart.asm.DebugPrinter$;
import codechicken.multipart.handler.MultipartProxy;
class DebugPrinterFunctionalTest {
@Test
void createsMissingDirectoriesOnlyWhenEnabled(@TempDir Path root) throws Exception {
for (boolean enabled : new boolean[] { false, true }) {
Path directory = root.resolve(Boolean.toString(enabled)).resolve("nested");
Object printer = printer(directory, enabled);
assertEquals(enabled, Files.isDirectory(directory));
dump(printer, "fixture/Example");
assertEquals(enabled, Files.exists(directory.resolve("fixture#Example.txt")));
assertEquals(enabled, Files.exists(directory));
}
}
@Test
void cleansOnlyImmediateChildrenAtStartupAndGatesDumps(@TempDir Path root) throws Exception {
Path expected = root.resolve("expected.txt");
ASMHelper.dump(classBytes(), expected.toFile(), false, false);
for (boolean enabled : new boolean[] { false, true }) {
Path directory = Files.createDirectory(root.resolve(Boolean.toString(enabled)));
Path stale = Files.write(directory.resolve("stale.txt"), new byte[] { 1, 2, 3 });
Path empty = Files.createDirectory(directory.resolve("empty"));
Path nested = Files.createDirectory(directory.resolve("nested"));
Path nestedFile = Files.write(nested.resolve("keep.txt"), new byte[] { 4, 5, 6 });
Object printer = printer(directory, enabled);
assertEquals(!enabled, Files.exists(stale));
assertEquals(!enabled, Files.exists(empty));
assertArrayEquals(new byte[] { 4, 5, 6 }, Files.readAllBytes(nestedFile), "Cleanup must not recurse");
if (!enabled) assertArrayEquals(new byte[] { 1, 2, 3 }, Files.readAllBytes(stale));
Path later = Files.write(directory.resolve("created-after-startup.txt"), new byte[] { 7 });
dump(printer, "fixture/Example");
dump(printer, "fixture/Second");
assertArrayEquals(new byte[] { 7 }, Files.readAllBytes(later), "Dumping must not repeat startup cleanup");
for (String name : new String[] { "fixture#Example.txt", "fixture#Second.txt" }) {
Path output = directory.resolve(name);
if (enabled) assertArrayEquals(Files.readAllBytes(expected), Files.readAllBytes(output));
else assertFalse(Files.exists(output));
}
}
}
@Test
void logsOnlyOnCumulativeThresholdCrossingsEvenWhenDumpingIsDisabled(@TempDir Path root) throws Exception {
for (boolean enabled : new boolean[] { false, true }) {
Object printer = printer(root.resolve(Boolean.toString(enabled)), enabled);
Logger logger = (Logger) printer.getClass().getMethod("logger").invoke(printer);
assertEquals("Multipart ASM", logger.getName());
Level previousLevel = logger.getLevel();
boolean previousAdditive = logger.isAdditive();
RecordingAppender appender = new RecordingAppender();
appender.start();
logger.addAppender(appender);
try {
logger.setLevel(Level.DEBUG);
logger.setAdditive(false);
Method defined = printer.getClass().getMethod("defined", String.class, byte[].class);
defined.invoke(printer, "first", new byte[15999]);
assertTrue(appender.messages.isEmpty());
defined.invoke(printer, "boundary", new byte[1]);
assertEquals(Arrays.asList(message(16000)), appender.messages);
defined.invoke(printer, "empty", new byte[0]);
defined.invoke(printer, "below-next", new byte[15999]);
assertEquals(Arrays.asList(message(16000)), appender.messages);
defined.invoke(printer, "next-boundary", new byte[1]);
defined.invoke(printer, "two-boundaries", new byte[32000]);
defined.invoke(printer, "below-next", new byte[1]);
assertEquals(Arrays.asList(message(16000), message(32000), message(64000)), appender.messages);
} finally {
logger.removeAppender(appender);
logger.setLevel(previousLevel);
logger.setAdditive(previousAdditive);
appender.stop();
}
}
}
private static String message(int bytes) {
return bytes + " bytes of permGen has been used by ASMMixinCompiler";
}
private static void dump(Object printer, String name) throws Exception {
printer.getClass().getMethod("dump", String.class, byte[].class).invoke(printer, name, classBytes());
}
private static byte[] classBytes() {
ClassWriter writer = new ClassWriter(0);
writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, "fixture/Example", null, "java/lang/Object", null);
writer.visitEnd();
return writer.toByteArray();
}
private static Object printer(Path directory, boolean enabled) throws Exception {
// Redirect only the hard-coded path; execute the real constructor and methods in an isolated loader.
ClassNode node = new ClassNode();
try (InputStream input = DebugPrinter$.class.getResourceAsStream("DebugPrinter$.class")) {
assertNotNull(input);
new ClassReader(input).accept(node, 0);
}
int paths = 0;
for (MethodNode method : node.methods) {
if (!method.name.equals("<init>")) continue;
for (AbstractInsnNode instruction : method.instructions.toArray()) {
if (instruction instanceof LdcInsnNode && "asm/multipart".equals(((LdcInsnNode) instruction).cst)) {
((LdcInsnNode) instruction).cst = directory.toAbsolutePath().toString();
paths++;
}
}
}
assertEquals(1, paths, "Never initialize a test copy with the live dev dump path");
ClassWriter writer = new ClassWriter(0);
node.accept(writer);
Class<?> type = new FixtureClassLoader(DebugPrinter$.class.getClassLoader()).define(writer.toByteArray());
ConfigTag tag = MultipartProxy.config().getTag("debug_asm");
String previous = tag.value;
try {
// In-memory override only: do not save or rewrite the development config file.
tag.value = Boolean.toString(enabled);
Object printer = type.getField("MODULE$").get(null);
assertEquals(enabled, type.getMethod("debug").invoke(printer));
assertEquals(directory.toAbsolutePath().toFile(), type.getMethod("dir").invoke(printer));
return printer;
} finally {
tag.value = previous;
}
}
private static final class FixtureClassLoader extends ClassLoader {
private FixtureClassLoader(ClassLoader parent) {
super(parent);
}
private Class<?> define(byte[] bytecode) {
return defineClass(null, bytecode, 0, bytecode.length);
}
}
private static final class RecordingAppender extends AbstractAppender {
private final List<String> messages = new ArrayList<>();
private RecordingAppender() {
super("fmp-debug-printer-test", null, null, false);
}
@Override
public void append(LogEvent event) {
assertEquals(Level.DEBUG, event.getLevel());
messages.add(event.getMessage().getFormattedMessage());
}
}
}
@@ -0,0 +1,647 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import org.junit.jupiter.api.Test;
import codechicken.lib.vec.Cuboid6;
import codechicken.lib.vec.Rotation;
import codechicken.lib.vec.Vector3;
import codechicken.microblock.BlockMicroMaterial;
import codechicken.microblock.CommonMicroClass;
import codechicken.microblock.CommonMicroblockClient;
import codechicken.microblock.CornerMicroClass;
import codechicken.microblock.CornerMicroClass$;
import codechicken.microblock.CornerMicroblock;
import codechicken.microblock.CornerPlacement;
import codechicken.microblock.CornerPlacement$;
import codechicken.microblock.CornerPlacementGrid$;
import codechicken.microblock.EdgeMicroClass;
import codechicken.microblock.EdgeMicroClass$;
import codechicken.microblock.EdgeMicroblock;
import codechicken.microblock.EdgePlacement;
import codechicken.microblock.EdgePlacement$;
import codechicken.microblock.EdgePlacementGrid$;
import codechicken.microblock.FaceMicroClass;
import codechicken.microblock.FaceMicroClass$;
import codechicken.microblock.FaceMicroblock;
import codechicken.microblock.FacePlacement$;
import codechicken.microblock.FacePlacementGrid$;
import codechicken.microblock.GrassMicroMaterial;
import codechicken.microblock.HollowMicroClass;
import codechicken.microblock.HollowMicroClass$;
import codechicken.microblock.HollowMicroblock;
import codechicken.microblock.HollowMicroblockClient;
import codechicken.microblock.HollowPlacement;
import codechicken.microblock.HollowPlacement$;
import codechicken.microblock.ISidedHollowConnect;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.MicroMaterialRegistry.IMicroMaterial;
import codechicken.microblock.Microblock;
import codechicken.microblock.MissingMicroMaterial;
import codechicken.microblock.MissingMicroMaterial$;
import codechicken.microblock.PostMicroClass;
import codechicken.microblock.PostMicroClass$;
import codechicken.microblock.PostMicroblock;
import codechicken.microblock.PostMicroblockClient;
import codechicken.microblock.TopMicroMaterial;
import codechicken.multipart.JPartialOcclusion;
import codechicken.multipart.MultiPartRegistry;
import codechicken.multipart.MultiPartRegistry.IPartFactory2;
import codechicken.multipart.TEdgePart;
import codechicken.multipart.TFacePart;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TNormalOcclusion;
import codechicken.multipart.TSlottedPart;
import codechicken.multipart.TileMultipart;
import scala.Tuple2;
import scala.collection.JavaConversions;
class DefaultContentFunctionalTest {
@Test
void registersTheExactBuiltInMicroblockClasses() throws Exception {
CommonMicroClass[] classes = CommonMicroClass.classes();
assertSame(FaceMicroClass$.MODULE$, classes[0]);
assertSame(HollowMicroClass$.MODULE$, classes[1]);
assertSame(CornerMicroClass$.MODULE$, classes[2]);
assertSame(EdgeMicroClass$.MODULE$, classes[3]);
for (int id = 4; id < classes.length; id++) {
assertNull(classes[id], "Unexpected microblock class ID " + id);
}
assertEquals(0, FaceMicroClass$.MODULE$.getClassId());
assertEquals(1, HollowMicroClass$.MODULE$.getClassId());
assertEquals(2, CornerMicroClass$.MODULE$.getClassId());
assertEquals(3, EdgeMicroClass$.MODULE$.getClassId());
Map<String, IPartFactory2> factories = partFactories();
Set<String> microblockTypes = new TreeSet<>();
for (String type : factories.keySet()) {
if (type.startsWith("mcr_")) {
microblockTypes.add(type);
}
}
assertEquals(
new TreeSet<>(Arrays.asList("mcr_cnr", "mcr_edge", "mcr_face", "mcr_hllw", "mcr_post")),
microblockTypes);
assertSame(CornerMicroClass$.MODULE$, factories.get("mcr_cnr"));
assertSame(EdgeMicroClass$.MODULE$, factories.get("mcr_edge"));
assertSame(FaceMicroClass$.MODULE$, factories.get("mcr_face"));
assertSame(HollowMicroClass$.MODULE$, factories.get("mcr_hllw"));
assertSame(PostMicroClass$.MODULE$, factories.get("mcr_post"));
}
@Test
void keepsFaceFactoryPlacementAndAllFortyTwoBounds() {
FaceMicroClass$ factory = FaceMicroClass$.MODULE$;
assertSame(factory, FacePlacement$.MODULE$.microClass());
assertSame(FacePlacementGrid$.MODULE$, FacePlacement$.MODULE$.placementGrid());
assertSame(factory.aBounds(), FaceMicroClass.aBounds());
assertEquals("mcr_face", factory.getName());
assertEquals(3, factory.itemSlot());
assertEquals(1f, factory.getResistanceFactor());
Cuboid6[] bounds = factory.aBounds();
assertEquals(256, bounds.length);
int populated = 0;
for (int side = 0; side < 6; side++) {
for (int size = 1; size < 8; size++) {
Cuboid6 expected = expectedFaceBounds(side, size / 8d);
Cuboid6 actual = bounds[size << 4 | side];
assertCuboid(expected, actual);
populated++;
}
}
for (Cuboid6 bound : bounds) {
if (bound != null) {
populated--;
}
}
assertEquals(0, populated, "Only the 6 sides by 7 thicknesses may be populated");
Microblock generated = factory.create(false, 0);
assertTrue(generated instanceof FaceMicroblock);
assertTrue(generated instanceof TFacePart);
for (int side = 0; side < 6; side++) {
generated.setShape(3, side);
FaceMicroblock face = (FaceMicroblock) generated;
assertSame(bounds[3 << 4 | side], face.getBounds());
assertEquals(side, face.getSlot());
assertEquals(generated.getIMaterial().isSolid(), face.solid(side));
}
}
@Test
void keepsCornerFactoryPlacementAndAllFiftySixBounds() {
CornerMicroClass$ factory = CornerMicroClass$.MODULE$;
assertSame(factory, CornerPlacement$.MODULE$.microClass());
assertSame(factory, CornerPlacement.microClass());
assertSame(CornerPlacementGrid$.MODULE$, CornerPlacement$.MODULE$.placementGrid());
assertSame(factory.aBounds(), CornerMicroClass.aBounds());
assertEquals("mcr_cnr", factory.getName());
assertEquals(CornerMicroblock.class, factory.baseTrait());
assertEquals(CommonMicroblockClient.class, factory.clientTrait());
assertEquals(7, factory.itemSlot());
assertEquals(1f, factory.getResistanceFactor());
Cuboid6[] bounds = factory.aBounds();
assertEquals(256, bounds.length);
int populated = 0;
for (int corner = 0; corner < 8; corner++) {
for (int size = 1; size < 8; size++) {
Cuboid6 expected = expectedCornerBounds(corner, size / 8d);
Cuboid6 actual = bounds[size << 4 | corner];
assertCuboid(expected, actual);
populated++;
}
}
for (Cuboid6 bound : bounds) {
if (bound != null) {
populated--;
}
}
assertEquals(0, populated, "Only the 8 corners by 7 sizes may be populated");
Microblock generated = factory.create(false, 0);
assertTrue(generated instanceof CornerMicroblock);
for (int slot = 7; slot < 15; slot++) {
generated.setShape(3, slot);
CornerMicroblock corner = (CornerMicroblock) generated;
assertSame(bounds[3 << 4 | slot - 7], corner.getBounds());
assertEquals(slot - 7, generated.getShape());
assertEquals(slot, corner.getSlot());
}
}
@Test
void keepsEdgeAndPostFactoriesBoundsAndGeneratedParts() {
EdgeMicroClass$ edgeFactory = EdgeMicroClass$.MODULE$;
assertSame(edgeFactory, EdgePlacement$.MODULE$.microClass());
assertSame(edgeFactory, EdgePlacement.microClass());
assertSame(EdgePlacementGrid$.MODULE$, EdgePlacement$.MODULE$.placementGrid());
assertSame(edgeFactory.aBounds(), EdgeMicroClass.aBounds());
assertEquals("mcr_edge", edgeFactory.getName());
assertEquals(EdgeMicroblock.class, edgeFactory.baseTrait());
assertEquals(CommonMicroblockClient.class, edgeFactory.clientTrait());
assertEquals(15, edgeFactory.itemSlot());
assertEquals(0.5f, edgeFactory.getResistanceFactor());
Cuboid6[] edgeBounds = edgeFactory.aBounds();
assertEquals(256, edgeBounds.length);
int populated = 0;
for (int edge = 0; edge < 12; edge++) {
for (int size = 1; size < 8; size++) {
assertCuboid(expectedEdgeBounds(edge, size / 8d), edgeBounds[size << 4 | edge]);
populated++;
}
}
assertEquals(populated, countPopulated(edgeBounds));
Microblock generatedEdge = edgeFactory.create(false, 0);
assertTrue(generatedEdge instanceof EdgeMicroblock);
assertTrue(generatedEdge instanceof TEdgePart);
for (int slot = 15; slot < 27; slot++) {
generatedEdge.setShape(3, slot);
EdgeMicroblock edge = (EdgeMicroblock) generatedEdge;
assertSame(edgeBounds[3 << 4 | slot - 15], edge.getBounds());
assertEquals(slot - 15, generatedEdge.getShape());
assertEquals(slot, edge.getSlot());
}
PostMicroClass$ postFactory = PostMicroClass$.MODULE$;
assertSame(postFactory.aBounds(), PostMicroClass.aBounds());
assertEquals("mcr_post", postFactory.getName());
assertEquals(PostMicroblock.class, postFactory.baseTrait());
assertEquals(PostMicroblockClient.class, postFactory.clientTrait());
assertEquals(0.5f, postFactory.getResistanceFactor());
Cuboid6[] postBounds = postFactory.aBounds();
assertEquals(256, postBounds.length);
populated = 0;
for (int axis = 0; axis < 3; axis++) {
for (int size = 2; size < 8; size += 2) {
assertCuboid(expectedPostBounds(axis, size), postBounds[size << 4 | axis]);
populated++;
}
}
assertEquals(populated, countPopulated(postBounds));
Microblock generatedPost = postFactory.create(false, 0);
assertTrue(generatedPost instanceof PostMicroblock);
assertTrue(generatedPost instanceof JPartialOcclusion);
assertTrue(generatedPost instanceof TNormalOcclusion);
PostMicroblock post = (PostMicroblock) generatedPost;
for (int axis = 0; axis < 3; axis++) {
generatedPost.setShape(4, axis);
assertSame(postBounds[4 << 4 | axis], post.getBounds());
assertEquals(edgeFactory.getClassId(), post.itemClassID());
assertEquals(0.5f, post.getResistanceFactor());
assertEquals(axis == 0, post.canPlaceTorchOnTop());
assertEquals(1, post.getOcclusionBoxes().size());
assertSame(post.getBounds(), post.getOcclusionBoxes().get(0));
assertEquals(post.getOcclusionBoxes(), post.getPartialOcclusionBoxes());
}
}
@Test
void keepsHollowFactoryBoundsAndGeneratedServerGeometry() {
HollowMicroClass$ factory = HollowMicroClass$.MODULE$;
assertSame(factory, HollowPlacement$.MODULE$.microClass());
assertSame(factory, HollowPlacement.microClass());
assertSame(HollowPlacement.HollowPlacementGrid$.MODULE$, HollowPlacement$.MODULE$.placementGrid());
assertSame(factory.pBoxes(), HollowMicroClass.pBoxes());
assertSame(factory.occBounds(), HollowMicroClass.occBounds());
assertEquals("mcr_hllw", factory.getName());
assertEquals(HollowMicroblock.class, factory.baseTrait());
assertEquals(HollowMicroblockClient.class, factory.clientTrait());
assertEquals(3, factory.itemSlot());
assertEquals(1f, factory.getResistanceFactor());
scala.collection.Seq<Cuboid6>[] partialBounds = factory.pBoxes();
Cuboid6[] occlusionBounds = factory.occBounds();
assertEquals(256, partialBounds.length);
assertEquals(256, occlusionBounds.length);
for (int side = 0; side < 6; side++) {
for (int size = 1; size < 8; size++) {
int shape = size << 4 | side;
List<Cuboid6> partial = JavaConversions.seqAsJavaList(partialBounds[shape]);
assertCuboids(expectedPartialBounds(side, size), partial);
assertCuboid(expectedHollowOcclusionBound(side, size), occlusionBounds[shape]);
}
}
assertEquals(42, countPopulated(partialBounds));
assertEquals(42, countPopulated(occlusionBounds));
Microblock generated = factory.create(false, 0);
assertTrue(generated instanceof HollowMicroblock);
assertTrue(generated instanceof TFacePart);
assertTrue(generated instanceof TNormalOcclusion);
HollowMicroblock hollow = (HollowMicroblock) generated;
assertEquals(factory.getClassId(), hollow.itemClassID());
assertEquals(8, hollow.getHollowSize());
assertTrue(hollow.allowCompleteOcclusion());
assertFalse(hollow.solid(0));
assertEquals(0x10, hollow.redstoneConductionMap());
for (int side = 0; side < 6; side++) {
generated.setShape(3, side);
int shape = 3 << 4 | side;
assertSame(FaceMicroClass$.MODULE$.aBounds()[shape], hollow.getBounds());
assertCuboids(JavaConversions.seqAsJavaList(partialBounds[shape]), hollow.getPartialOcclusionBoxes());
assertCuboids(expectedCollisionBounds(side, 3, 8), hollow.getCollisionBoxes());
assertCuboids(expectedOcclusionBoxes(side, 3, 8), hollow.getOcclusionBoxes());
assertEquals(4, hollow.getSubParts().size());
for (int i = 0; i < 4; i++) {
assertEquals(0, hollow.getSubParts().get(i).data);
assertCuboid(hollow.getCollisionBoxes().get(i), hollow.getSubParts().get(i));
}
}
}
@Test
void keepsConnectedHollowSizesAndAllDynamicGeometry() {
ConnectorPart connector = new ConnectorPart();
TileMultipart tile = new TileMultipart() {
@Override
public TMultiPart partMap(int slot) {
return slot == 6 ? connector : null;
}
};
connector.bind(tile);
int material = MicroMaterialRegistry.materialID("minecraft:stone");
assertTrue(material >= 0);
Microblock generated = HollowMicroClass$.MODULE$.create(false, material);
generated.setShape(3, 0);
generated.bind(tile);
HollowMicroblock hollow = (HollowMicroblock) generated;
for (int size = 1; size < 12; size++) {
connector.size = size;
for (int side = 0; side < 6; side++) {
generated.setShape(3, side);
assertEquals(size, hollow.getHollowSize());
assertCuboids(expectedCollisionBounds(side, 3, size), hollow.getCollisionBoxes());
assertCuboids(expectedOcclusionBoxes(side, 3, size), hollow.getOcclusionBoxes());
assertEquals(4, hollow.getSubParts().size());
for (int i = 0; i < 4; i++) {
assertEquals(0, hollow.getSubParts().get(i).data);
assertCuboid(hollow.getCollisionBoxes().get(i), hollow.getSubParts().get(i));
}
}
}
}
@Test
void registersTheExactOrderedBuiltInMaterialsAndRemaps() throws Exception {
List<String> expectedNames = new ArrayList<>();
Map<String, String> expectedRemaps = new HashMap<>();
add(expectedNames, expectedRemaps, Blocks.stone, "minecraft:stone", 0);
add(expectedNames, expectedRemaps, Blocks.dirt, "minecraft:dirt", 2);
add(expectedNames, expectedRemaps, Blocks.cobblestone, "minecraft:cobblestone", 0);
add(expectedNames, expectedRemaps, Blocks.planks, "minecraft:planks", 5);
add(expectedNames, expectedRemaps, Blocks.log, "minecraft:log", 3);
add(expectedNames, expectedRemaps, Blocks.log2, "minecraft:log2", 1, "tile.log2");
add(expectedNames, expectedRemaps, Blocks.leaves, "minecraft:leaves", 3);
add(expectedNames, expectedRemaps, Blocks.leaves2, "minecraft:leaves2", 1, "tile.leaves2");
add(expectedNames, expectedRemaps, Blocks.sponge, "minecraft:sponge", 0);
add(expectedNames, expectedRemaps, Blocks.glass, "minecraft:glass", 0);
add(expectedNames, expectedRemaps, Blocks.lapis_block, "minecraft:lapis_block", 0);
add(expectedNames, expectedRemaps, Blocks.sandstone, "minecraft:sandstone", 2);
add(expectedNames, expectedRemaps, Blocks.wool, "minecraft:wool", 15);
add(expectedNames, expectedRemaps, Blocks.gold_block, "minecraft:gold_block", 0);
add(expectedNames, expectedRemaps, Blocks.iron_block, "minecraft:iron_block", 0);
add(expectedNames, expectedRemaps, Blocks.brick_block, "minecraft:brick_block", 0);
add(expectedNames, expectedRemaps, Blocks.bookshelf, "minecraft:bookshelf", 0);
add(expectedNames, expectedRemaps, Blocks.mossy_cobblestone, "minecraft:mossy_cobblestone", 0);
add(expectedNames, expectedRemaps, Blocks.obsidian, "minecraft:obsidian", 0);
add(expectedNames, expectedRemaps, Blocks.diamond_block, "minecraft:diamond_block", 0);
add(expectedNames, expectedRemaps, Blocks.ice, "minecraft:ice", 0);
add(expectedNames, expectedRemaps, Blocks.snow, "minecraft:snow", 0);
add(expectedNames, expectedRemaps, Blocks.clay, "minecraft:clay", 0);
add(expectedNames, expectedRemaps, Blocks.netherrack, "minecraft:netherrack", 0);
add(expectedNames, expectedRemaps, Blocks.soul_sand, "minecraft:soul_sand", 0);
add(expectedNames, expectedRemaps, Blocks.glowstone, "minecraft:glowstone", 0);
add(expectedNames, expectedRemaps, Blocks.stonebrick, "minecraft:stonebrick", 3);
add(expectedNames, expectedRemaps, Blocks.nether_brick, "minecraft:nether_brick", 0);
add(expectedNames, expectedRemaps, Blocks.end_stone, "minecraft:end_stone", 0);
add(expectedNames, expectedRemaps, Blocks.emerald_block, "minecraft:emerald_block", 0);
add(expectedNames, expectedRemaps, Blocks.redstone_block, "minecraft:redstone_block", 0);
add(expectedNames, expectedRemaps, Blocks.quartz_block, "minecraft:quartz_block", 0);
add(expectedNames, expectedRemaps, Blocks.stained_hardened_clay, "minecraft:stained_hardened_clay", 15);
add(expectedNames, expectedRemaps, Blocks.hardened_clay, "minecraft:hardened_clay", 0);
add(expectedNames, expectedRemaps, Blocks.coal_block, "minecraft:coal_block", 0);
add(expectedNames, expectedRemaps, Blocks.packed_ice, "minecraft:packed_ice", 0);
add(expectedNames, expectedRemaps, Blocks.stained_glass, "minecraft:stained_glass", 15);
add(expectedNames, expectedRemaps, Blocks.grass, "minecraft:grass", 0);
add(expectedNames, expectedRemaps, Blocks.mycelium, "minecraft:mycelium", 0);
expectedNames.add(MissingMicroMaterial.key());
for (int meta = 16; meta < 32; meta++) {
expectedNames.add(
codechicken.microblock.BlockMicroMaterial
.materialKey(ForgeMultipartFunctionalTestMod.illuminatedLamp, meta));
}
Collections.sort(expectedNames);
Tuple2<String, IMicroMaterial>[] idMap = MicroMaterialRegistry.getIdMap();
List<String> actualNames = new ArrayList<>(idMap.length);
for (Tuple2<String, IMicroMaterial> entry : idMap) {
actualNames.add(entry._1());
if ("minecraft:grass".equals(entry._1())) {
assertEquals(GrassMicroMaterial.class, entry._2().getClass());
} else if ("minecraft:mycelium".equals(entry._1())) {
assertEquals(TopMicroMaterial.class, entry._2().getClass());
} else if (MissingMicroMaterial.key().equals(entry._1())) {
assertSame(MissingMicroMaterial$.MODULE$, entry._2());
} else if (entry._1().startsWith("ForgeMultipartTests:illuminated_lamp_")) {
assertEquals(codechicken.multipart.examples.IlluminatedMicroMaterial.class, entry._2().getClass());
} else {
assertEquals(BlockMicroMaterial.class, entry._2().getClass(), entry._1());
}
}
assertEquals(121, expectedNames.size());
assertEquals(expectedNames, actualNames);
assertEquals(expectedRemaps, materialRemaps());
}
private static void add(List<String> names, Map<String, String> remaps, Block block, String registeredName,
int maxMeta) {
add(names, remaps, block, registeredName, maxMeta, block.getUnlocalizedName());
}
private static List<Cuboid6> expectedPartialBounds(int side, int size) {
double thickness = size / 8d;
double width = 1 / 8d;
return transform(
side,
Arrays.asList(
new Cuboid6(0, 0, 0, width, thickness, 1),
new Cuboid6(1 - width, 0, 0, 1, thickness, 1),
new Cuboid6(width, 0, 0, 1 - width, thickness, width),
new Cuboid6(width, 0, 1 - width, 1 - width, thickness, 1)));
}
private static Cuboid6 expectedHollowOcclusionBound(int side, int size) {
return new Cuboid6(1 / 8d, 0, 1 / 8d, 7 / 8d, size / 8d, 7 / 8d)
.apply(Rotation.sideRotations[side].at(Vector3.center));
}
private static List<Cuboid6> expectedCollisionBounds(int side, int partSize, int hollowSize) {
double d1 = 0.5 - hollowSize / 32d;
double d2 = 0.5 + hollowSize / 32d;
double thickness = partSize / 8d;
return transform(
side,
Arrays.asList(
new Cuboid6(0, 0, 0, 1, thickness, d1),
new Cuboid6(0, 0, d2, 1, thickness, 1),
new Cuboid6(0, 0, d1, d1, thickness, d2),
new Cuboid6(d2, 0, d1, 1, thickness, d2)));
}
private static List<Cuboid6> expectedOcclusionBoxes(int side, int partSize, int hollowSize) {
Cuboid6 c = expectedHollowOcclusionBound(side, partSize);
double d1 = 0.5 - hollowSize / 32d;
double d2 = 0.5 + hollowSize / 32d;
double x1 = c.min.x;
double x2 = c.max.x;
double y1 = c.min.y;
double y2 = c.max.y;
double z1 = c.min.z;
double z2 = c.max.z;
switch (side) {
case 0:
case 1:
return Arrays.asList(
new Cuboid6(d2, y1, d1, x2, y2, d2),
new Cuboid6(x1, y1, d1, d1, y2, d2),
new Cuboid6(x1, y1, d2, x2, y2, z2),
new Cuboid6(x1, y1, z1, x2, y2, d1));
case 2:
case 3:
return Arrays.asList(
new Cuboid6(d1, d2, z1, d2, y2, z2),
new Cuboid6(d1, y1, z1, d2, d1, z2),
new Cuboid6(d2, y1, z1, x2, y2, z2),
new Cuboid6(x1, y1, z1, d1, y2, z2));
case 4:
case 5:
return Arrays.asList(
new Cuboid6(x1, d1, d2, x2, d2, z2),
new Cuboid6(x1, d1, z1, x2, d2, d1),
new Cuboid6(x1, d2, z1, x2, y2, z2),
new Cuboid6(x1, y1, z1, x2, d1, z2));
default:
throw new AssertionError(side);
}
}
private static List<Cuboid6> transform(int side, List<Cuboid6> bounds) {
List<Cuboid6> transformed = new ArrayList<>(bounds.size());
for (Cuboid6 bound : bounds) {
transformed.add(bound.apply(Rotation.sideRotations[side].at(Vector3.center)));
}
return transformed;
}
private static Cuboid6 expectedFaceBounds(int side, double thickness) {
switch (side) {
case 0:
return new Cuboid6(0, 0, 0, 1, thickness, 1);
case 1:
return new Cuboid6(0, 1 - thickness, 0, 1, 1, 1);
case 2:
return new Cuboid6(0, 0, 0, 1, 1, thickness);
case 3:
return new Cuboid6(0, 0, 1 - thickness, 1, 1, 1);
case 4:
return new Cuboid6(0, 0, 0, thickness, 1, 1);
case 5:
return new Cuboid6(1 - thickness, 0, 0, 1, 1, 1);
default:
throw new AssertionError(side);
}
}
private static Cuboid6 expectedCornerBounds(int corner, double size) {
double minX = (corner & 4) == 0 ? 0 : 1 - size;
double minY = (corner & 1) == 0 ? 0 : 1 - size;
double minZ = (corner & 2) == 0 ? 0 : 1 - size;
return new Cuboid6(minX, minY, minZ, minX + size, minY + size, minZ + size);
}
private static Cuboid6 expectedEdgeBounds(int edge, double size) {
switch (edge >> 2) {
case 0:
return axisBounds((edge & 2) == 0 ? 0 : 1 - size, 0, (edge & 1) == 0 ? 0 : 1 - size, size, 1, size);
case 1:
return axisBounds((edge & 1) == 0 ? 0 : 1 - size, (edge & 2) == 0 ? 0 : 1 - size, 0, size, size, 1);
case 2:
return axisBounds(0, (edge & 1) == 0 ? 0 : 1 - size, (edge & 2) == 0 ? 0 : 1 - size, 1, size, size);
default:
throw new AssertionError(edge);
}
}
private static Cuboid6 expectedPostBounds(int axis, int size) {
double min = 0.5 - size / 16d;
double width = size / 8d;
switch (axis) {
case 0:
return axisBounds(min, 0, min, width, 1, width);
case 1:
return axisBounds(min, min, 0, width, width, 1);
case 2:
return axisBounds(0, min, min, 1, width, width);
default:
throw new AssertionError(axis);
}
}
private static Cuboid6 axisBounds(double minX, double minY, double minZ, double sizeX, double sizeY, double sizeZ) {
return new Cuboid6(minX, minY, minZ, minX + sizeX, minY + sizeY, minZ + sizeZ);
}
private static int countPopulated(Cuboid6[] bounds) {
int populated = 0;
for (Cuboid6 bound : bounds) {
if (bound != null) {
populated++;
}
}
return populated;
}
private static int countPopulated(scala.collection.Seq<Cuboid6>[] bounds) {
int populated = 0;
for (scala.collection.Seq<Cuboid6> bound : bounds) {
if (bound != null) {
populated++;
}
}
return populated;
}
private static void assertCuboids(Iterable<Cuboid6> expected, Iterable<Cuboid6> actual) {
Iterator<Cuboid6> expectedIterator = expected.iterator();
Iterator<Cuboid6> actualIterator = actual.iterator();
while (expectedIterator.hasNext()) {
assertTrue(actualIterator.hasNext());
assertCuboid(expectedIterator.next(), actualIterator.next());
}
assertFalse(actualIterator.hasNext());
}
private static void assertCuboid(Cuboid6 expected, Cuboid6 actual) {
assertEquals(expected.min.x, actual.min.x, 1e-12);
assertEquals(expected.min.y, actual.min.y, 1e-12);
assertEquals(expected.min.z, actual.min.z, 1e-12);
assertEquals(expected.max.x, actual.max.x, 1e-12);
assertEquals(expected.max.y, actual.max.y, 1e-12);
assertEquals(expected.max.z, actual.max.z, 1e-12);
}
private static void add(List<String> names, Map<String, String> remaps, Block block, String registeredName,
int maxMeta, String oldName) {
for (int meta = 0; meta <= maxMeta; meta++) {
String suffix = meta == 0 ? "" : "_" + meta;
names.add(registeredName + suffix);
remaps.put(oldName + suffix, registeredName + suffix);
}
}
@SuppressWarnings("unchecked")
private static Map<String, IPartFactory2> partFactories() throws Exception {
Field field = MultiPartRegistry.class.getDeclaredField("typeMap");
field.setAccessible(true);
return (Map<String, IPartFactory2>) field.get(null);
}
@SuppressWarnings("unchecked")
private static Map<String, String> materialRemaps() throws Exception {
Field field = MicroMaterialRegistry.class.getDeclaredField("remap");
field.setAccessible(true);
return (Map<String, String>) field.get(null);
}
private static final class ConnectorPart extends TMultiPart implements TSlottedPart, ISidedHollowConnect {
private int size;
@Override
public String getType() {
return "multipart_test:hollow_connector";
}
@Override
public int getSlotMask() {
return 1 << 6;
}
@Override
public int getHollowSize(int side) {
return size;
}
}
}
@@ -0,0 +1,132 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.*;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
import net.minecraft.nbt.NBTTagCompound;
import org.junit.jupiter.api.Test;
import codechicken.lib.data.MCDataInput;
import codechicken.lib.data.MCDataOutputWrapper;
import codechicken.lib.vec.Cuboid6;
import codechicken.microblock.EdgeMicroClass;
import codechicken.microblock.EdgeMicroClass$;
import codechicken.microblock.EdgeMicroblock;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.Microblock;
import codechicken.microblock.MicroblockGenerator;
class EdgeMicroblockTraitsFunctionalTest {
@Test
void generatedEdgeKeepsClassIdentityAndAllEightyFourBounds() {
Microblock part = MicroblockGenerator.create(EdgeMicroClass$.MODULE$, 0, false);
EdgeMicroblock edgePart = (EdgeMicroblock) part;
assertSame(EdgeMicroClass$.MODULE$, edgePart.microClass());
assertSame(EdgeMicroClass$.MODULE$, part.microClass());
assertEquals("mcr_edge", part.getType());
int[][] axisBits = { { 2, 0, 1 }, { 1, 2, 0 }, { 0, 1, 2 } };
for (int size = 1; size <= 7; size++) {
for (int edge = 0; edge < 12; edge++) {
part.setShape(size, edge + 15);
assertEquals(size, part.getSize());
assertEquals(edge + 15, edgePart.getSlot());
assertEquals(1 << (edge + 15), edgePart.getSlotMask());
assertFalse(edgePart.conductsRedstone());
Cuboid6 bounds = edgePart.getBounds();
assertSame(EdgeMicroClass.aBounds()[size * 16 + edge], bounds);
double distance = size / 8D;
double[] min = { bounds.min.x, bounds.min.y, bounds.min.z };
double[] max = { bounds.max.x, bounds.max.y, bounds.max.z };
for (int axis = 0; axis < 3; axis++) {
int bit = axisBits[edge / 4][axis];
boolean positive = (edge & bit) != 0;
assertEquals(positive ? 1 - distance : 0, min[axis], 1e-12);
assertEquals(bit == 0 || positive ? 1 : distance, max[axis], 1e-12);
}
}
}
}
@Test
void boundsUseSignedShapeIndexAndTheLiveReplaceableArray() {
Microblock part = MicroblockGenerator.create(EdgeMicroClass$.MODULE$, 0, false);
EdgeMicroblock edge = (EdgeMicroblock) part;
for (int shape : new int[] { 0, 12, 28, 127 }) {
part.shape_$eq((byte) shape);
assertNull(edge.getBounds());
}
for (int shape = -128; shape < 0; shape++) {
part.shape_$eq((byte) shape);
assertThrows(ArrayIndexOutOfBoundsException.class, edge::getBounds);
}
Cuboid6[] original = EdgeMicroClass.aBounds();
Cuboid6[] replacement = new Cuboid6[256];
Cuboid6 sentinel = new Cuboid6(0.1, 0.2, 0.3, 0.4, 0.5, 0.6);
replacement[35] = sentinel;
part.setShape(2, 18);
try {
EdgeMicroClass.aBounds_$eq(replacement);
assertSame(sentinel, edge.getBounds());
replacement[35] = null;
assertNull(edge.getBounds());
EdgeMicroClass.aBounds_$eq(new Cuboid6[1]);
assertThrows(ArrayIndexOutOfBoundsException.class, edge::getBounds);
EdgeMicroClass.aBounds_$eq(null);
assertThrows(NullPointerException.class, edge::getBounds);
} finally {
EdgeMicroClass.aBounds_$eq(original);
}
assertSame(original[35], edge.getBounds());
}
@Test
void generatedEdgesKeepThePackedShapeInNbtAndDescriptions() {
Microblock part = MicroblockGenerator.create(EdgeMicroClass$.MODULE$, 0, false);
Microblock loaded = MicroblockGenerator.create(EdgeMicroClass$.MODULE$, 0, false);
ByteArrayOutputStream prefixBytes = new ByteArrayOutputStream();
MicroMaterialRegistry.writeMaterialID(new MCDataOutputWrapper(new DataOutputStream(prefixBytes)), 0);
byte[] prefix = prefixBytes.toByteArray();
for (int size = 1; size <= 7; size++) {
for (int edge = 0; edge < 12; edge++) {
byte shape = (byte) (size * 16 + edge);
part.setShape(size, edge + 15);
NBTTagCompound tag = new NBTTagCompound();
part.save(tag);
assertEquals(shape, tag.getByte("shape"));
assertEquals(MicroMaterialRegistry.materialName(0), tag.getString("material"));
loaded.load(tag);
assertEquals(shape, loaded.shape());
assertEquals(0, loaded.material());
assertEquals(edge + 15, ((EdgeMicroblock) loaded).getSlot());
assertSame(part.getBounds(), loaded.getBounds());
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
part.writeDesc(new MCDataOutputWrapper(new DataOutputStream(bytes)));
byte[] expected = Arrays.copyOf(prefix, prefix.length + 1);
expected[prefix.length] = shape;
assertArrayEquals(expected, bytes.toByteArray());
AtomicInteger reads = new AtomicInteger();
MCDataInput input = (MCDataInput) Proxy.newProxyInstance(
getClass().getClassLoader(),
new Class<?>[] { MCDataInput.class },
(proxy, method, args) -> {
assertEquals("readByte", method.getName());
reads.incrementAndGet();
return shape;
});
loaded.setShape(2, 15);
loaded.readDesc(input);
assertEquals(1, reads.get());
assertEquals(shape, loaded.shape());
assertEquals(edge + 15, ((EdgeMicroblock) loaded).getSlot());
}
}
}
}
@@ -0,0 +1,40 @@
package codechicken.multipart.test;
import java.lang.reflect.Array;
import java.lang.reflect.Proxy;
import org.apache.logging.log4j.Logger;
import codechicken.multipart.handler.MultipartProxy;
/**
* Runs an action with ForgeMultipart's logger detached, for tests that deliberately drive a path which logs at ERROR.
* Those lines are correct behaviour, but in a green run they read as failures.
*
* <p>
* The swap is global and not thread safe; callers run on the server thread inside one synchronous call.
*/
final class ExpectedErrorLog {
/** A reflective proxy rather than a subclass, so it does not depend on Forge's log4j-api version. */
private static final Logger SILENT = (Logger) Proxy
.newProxyInstance(Logger.class.getClassLoader(), new Class<?>[] { Logger.class }, (proxy, method, args) -> {
Class<?> returnType = method.getReturnType();
if (returnType == String.class) return "";
if (returnType == void.class || !returnType.isPrimitive()) return null;
// Boxed zero/false for any primitive return, without enumerating them.
return Array.get(Array.newInstance(returnType, 1), 0);
});
private ExpectedErrorLog() {}
static void silence(Runnable action) {
Logger original = MultipartProxy.logger();
MultipartProxy.logger_$eq(SILENT);
try {
action.run();
} finally {
MultipartProxy.logger_$eq(original);
}
}
}
@@ -0,0 +1,105 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.*;
import java.lang.reflect.Proxy;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import codechicken.lib.vec.Cuboid6;
import codechicken.microblock.FaceMicroClass;
import codechicken.microblock.FaceMicroClass$;
import codechicken.microblock.FaceMicroblock;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.MicroMaterialRegistry.IMicroMaterial;
import codechicken.microblock.Microblock;
import codechicken.microblock.MicroblockGenerator;
import scala.Tuple2;
class FaceMicroblockTraitsFunctionalTest {
@Test
void generatedFaceSelectsFactoryBoundsForEverySupportedShape() {
Microblock part = MicroblockGenerator.create(FaceMicroClass$.MODULE$, 0, false);
FaceMicroblock face = (FaceMicroblock) part;
assertSame(FaceMicroClass$.MODULE$, face.microClass());
assertSame(FaceMicroClass$.MODULE$, part.microClass());
for (int size = 1; size <= 7; size++) {
for (int side = 0; side < 6; side++) {
part.setShape(size, side);
Cuboid6 bounds = face.getBounds();
assertSame(FaceMicroClass.aBounds()[size << 4 | side], bounds);
double thickness = size / 8D;
int axis = side / 2 == 0 ? 1 : side / 2 == 1 ? 2 : 0;
double[] min = { bounds.min.x, bounds.min.y, bounds.min.z };
double[] max = { bounds.max.x, bounds.max.y, bounds.max.z };
for (int coordinate = 0; coordinate < 3; coordinate++) {
assertEquals(coordinate == axis && (side & 1) != 0 ? 1 - thickness : 0, min[coordinate], 1e-12);
assertEquals(coordinate == axis && (side & 1) == 0 ? thickness : 1, max[coordinate], 1e-12);
}
}
}
}
@Test
void boundsLookupKeepsSignedIndexingNullEntriesAndLiveArrayReplacement() {
Microblock part = MicroblockGenerator.create(FaceMicroClass$.MODULE$, 0, false);
FaceMicroblock face = (FaceMicroblock) part;
part.shape_$eq((byte) 0);
assertNull(face.getBounds());
part.shape_$eq((byte) 127);
assertNull(face.getBounds());
for (int shape = -128; shape < 0; shape++) {
part.shape_$eq((byte) shape);
assertThrows(ArrayIndexOutOfBoundsException.class, face::getBounds);
}
Cuboid6[] original = FaceMicroClass.aBounds();
Cuboid6[] replacement = new Cuboid6[256];
Cuboid6 sentinel = new Cuboid6(0.2, 0.3, 0.4, 0.5, 0.6, 0.7);
replacement[35] = sentinel;
part.shape_$eq((byte) 35);
try {
FaceMicroClass.aBounds_$eq(replacement);
assertSame(sentinel, face.getBounds());
replacement[35] = null;
assertNull(face.getBounds());
FaceMicroClass.aBounds_$eq(new Cuboid6[1]);
assertThrows(ArrayIndexOutOfBoundsException.class, face::getBounds);
} finally {
FaceMicroClass.aBounds_$eq(original);
}
assertSame(original[35], face.getBounds());
}
@Test
void solidityDelegatesToCurrentMaterialAndIgnoresTheSide() {
Microblock part = MicroblockGenerator.create(FaceMicroClass$.MODULE$, 0, false);
FaceMicroblock face = (FaceMicroblock) part;
Tuple2<String, IMicroMaterial>[] materials = MicroMaterialRegistry.getIdMap();
Tuple2<String, IMicroMaterial> original = materials[0];
AtomicBoolean solid = new AtomicBoolean();
AtomicInteger calls = new AtomicInteger();
IMicroMaterial material = (IMicroMaterial) Proxy.newProxyInstance(
getClass().getClassLoader(),
new Class<?>[] { IMicroMaterial.class },
(proxy, method, args) -> {
assertEquals("isSolid", method.getName());
calls.incrementAndGet();
return solid.get();
});
try {
materials[0] = new Tuple2<>(original._1(), material);
for (boolean value : new boolean[] { false, true }) {
solid.set(value);
for (int side : new int[] { -1, 0, 1, 2, 3, 4, 5, 6 }) assertEquals(value, face.solid(side));
}
assertEquals(16, calls.get());
materials[0] = new Tuple2<>(original._1(), null);
assertThrows(NullPointerException.class, () -> face.solid(0));
} finally {
materials[0] = original;
}
}
}
@@ -0,0 +1,695 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Set;
import java.util.TreeSet;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraftforge.fluids.IFluidHandler;
import org.junit.jupiter.api.Test;
import codechicken.lib.data.MCDataInput;
import codechicken.lib.data.MCDataOutput;
import codechicken.lib.data.MCDataOutputWrapper;
import codechicken.lib.vec.Cuboid6;
import codechicken.microblock.FaceMicroClass$;
import codechicken.microblock.HollowMicroClass$;
import codechicken.microblock.Microblock;
import codechicken.microblock.MicroblockGenerator;
import codechicken.multipart.JPartialOcclusion;
import codechicken.multipart.MultiPartRegistry;
import codechicken.multipart.MultipartHelper;
import codechicken.multipart.TFacePart;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TileMultipart;
import codechicken.multipart.TileMultipartClient;
import codechicken.multipart.asm.MultipartMixinFactory;
import codechicken.multipart.scalatraits.JInventoryTile;
import codechicken.multipart.scalatraits.TFluidHandlerTile;
import codechicken.multipart.scalatraits.TIInventoryTile;
import codechicken.multipart.scalatraits.TRandomDisplayTickTile;
import codechicken.multipart.scalatraits.TSlottedTile;
import codechicken.multipart.scalatraits.TTileChangeTile;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import scala.collection.JavaConversions;
import scala.collection.Seq;
import scala.collection.immutable.Nil$;
class ForgeEnvironmentSmokeTest {
@Test
void renderIdRemainsUninitializedOnTheDedicatedServerAndSharesBlockState() {
int previous = TileMultipart.renderID();
assertEquals(-1, previous);
assertEquals(previous, TileMultipart.getRenderID());
try {
TileMultipart.renderID_$eq(37);
assertEquals(37, codechicken.multipart.handler.MultipartProxy.block().getRenderType());
assertEquals(37, codechicken.multipart.TileMultipart$.MODULE$.renderID());
assertEquals(37, TileMultipart.getRenderID());
TileMultipart.setRenderID(38);
assertEquals(38, codechicken.multipart.handler.MultipartProxy.block().getRenderType());
assertEquals(38, TileMultipart.renderID());
} finally {
TileMultipart.renderID_$eq(previous);
}
}
@Test
void reachesServerStartedWithWorldAndMultipartModsLoaded() {
assertTrue(ForgeMultipartFunctionalTestMod.preInitialized);
assertTrue(ForgeMultipartFunctionalTestMod.initialized);
assertTrue(ForgeMultipartFunctionalTestMod.postInitialized);
assertTrue(ForgeMultipartFunctionalTestMod.serverAboutToStart);
assertTrue(ForgeMultipartFunctionalTestMod.serverStarted);
assertTrue(FMLCommonHandler.instance().getSide().isServer());
assertTrue(Loader.isModLoaded("ForgeMultipart"));
assertTrue(Loader.isModLoaded("ForgeMicroblock"));
assertTrue(Loader.isModLoaded("McMultipart"));
MinecraftServer server = MinecraftServer.getServer();
assertNotNull(server);
assertNotNull(server.worldServers);
assertTrue(server.worldServers.length > 0);
assertNotNull(server.worldServers[0]);
}
/**
* Microblock classes are generated by ASM at runtime. TFacePart's members are now Java interface defaults rather
* than Scala trait forwarders, so a generated class inherits them instead of declaring its own; this checks the JVM
* resolves them for a class that never existed at compile time.
*/
@Test
void generatedMicroblockInheritsFacePartDefaults() {
Microblock face = MicroblockGenerator.create(FaceMicroClass$.MODULE$, 0, false);
Microblock hollow = MicroblockGenerator.create(HollowMicroClass$.MODULE$, 0, false);
assertTrue(face instanceof TFacePart);
assertEquals(0, ((TFacePart) face).redstoneConductionMap());
// HollowMicroblock overrides both members, so its generated class must not pick up the defaults.
assertTrue(hollow instanceof TFacePart);
assertEquals(0x10, ((TFacePart) hollow).redstoneConductionMap());
assertFalse(((TFacePart) hollow).solid(0));
}
@Test
void generatedMicroblockInitializesAndDispatchesAnExternalScalaTrait() throws Exception {
BitSet traits = new BitSet();
traits.set(FaceMicroClass$.MODULE$.baseTraitId());
traits.set(ForgeMultipartFunctionalTestMod.externalScalaMicroblockTraitId);
Seq<Object> arguments = JavaConversions.asScalaBuffer(Collections.<Object>singletonList(0)).toList();
Microblock microblock = (Microblock) MicroblockGenerator.construct(traits, arguments);
Class<?> trait = Class.forName("codechicken.multipart.test.ExternalScalaMicroblockFixture");
assertTrue(trait.isInterface());
assertTrue(trait.isInstance(microblock));
assertTrue(microblock.shouldRenderDynamic());
assertEquals(41, microblock.getLightValue());
assertEquals(41, ((Number) microblock.getClass().getMethod("fixtureState").invoke(microblock)).intValue());
}
/**
* Part registration needs FML's active mod container, so none of this is reachable from a plain JVM test. Startup
* exercises both overloads downstream depends on: Content registers through the deprecated IPartFactory array form,
* and each microblock class registers through the IPartFactory2 varargs form.
*/
@Test
void registryResolvesPartsRegisteredThroughBothFactoryOverloads() throws Exception {
assertTrue(MultiPartRegistry.loaded(), "Registration must be closed once the server has started");
// mc_torch comes from the deprecated IPartFactory array overload.
TMultiPart torch = MultiPartRegistry.loadPart("mc_torch", null);
assertNotNull(torch);
assertEquals("mc_torch", torch.getType());
// mcr_face comes from the IPartFactory2 varargs overload. Its factory reads the tag, so it needs a real one;
// an absent material name resolves to the missing-material placeholder rather than failing.
TMultiPart face = MultiPartRegistry.loadPart("mcr_face", new NBTTagCompound());
assertNotNull(face);
assertEquals("mcr_face", face.getType());
assertNotNull(MultiPartRegistry.getModContainer("mc_torch"));
assertNotNull(MultiPartRegistry.getModContainer("mcr_face"));
}
@Test
void partIdsRoundTripThroughTheRegistryCarrier() {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
MCDataOutput output = new MCDataOutputWrapper(new DataOutputStream(bytes));
TMultiPart torch = MultiPartRegistry.loadPart("mc_torch", null);
MultiPartRegistry.writePartID(output, torch);
TMultiPart read = MultiPartRegistry.readPart(input(bytes.toByteArray()));
assertNotNull(read);
assertEquals("mc_torch", read.getType());
}
/** CodeChickenLib has no stream-backed MCDataInput, so the carrier reads are proxied. */
private static MCDataInput input(byte[] bytes) {
DataInputStream data = new DataInputStream(new ByteArrayInputStream(bytes));
return (MCDataInput) Proxy.newProxyInstance(
MCDataInput.class.getClassLoader(),
new Class<?>[] { MCDataInput.class },
(proxy, method, arguments) -> {
switch (method.getName()) {
case "readUByte":
return (short) data.readUnsignedByte();
case "readUShort":
return data.readUnsignedShort();
case "readInt":
return data.readInt();
default:
throw new AssertionError("Unexpected read method: " + method.getName());
}
});
}
@Test
void generatesAndCachesSlottedTileClass() throws Exception {
int traitId = MultipartMixinFactory.getId(TSlottedTile.class.getName().replace('.', '/'));
assertFalse(traitId < 0);
BitSet traits = new BitSet();
traits.set(traitId);
Object first = MultipartMixinFactory.construct(traits, Nil$.MODULE$);
Object second = MultipartMixinFactory.construct(traits, Nil$.MODULE$);
Class<?> trait = Class.forName("codechicken.multipart.scalatraits.TSlottedTile");
assertTrue(first instanceof TileMultipart);
assertTrue(first instanceof TSlottedTile);
assertTrue(trait.isInterface());
assertNotSame(first, second);
assertSame(first.getClass(), second.getClass());
assertEquals(0, trait.getDeclaredFields().length);
Set<String> signatures = new TreeSet<>();
for (java.lang.reflect.Method method : trait.getDeclaredMethods()) {
signatures.add(method.getName() + org.objectweb.asm.Type.getMethodDescriptor(method));
}
assertEquals(
new TreeSet<>(
Arrays.asList(
"bindPart(Lcodechicken/multipart/TMultiPart;)V",
"canAddPart(Lcodechicken/multipart/TMultiPart;)Z",
"clearParts()V",
"codechicken$multipart$scalatraits$TSlottedTile$$super$bindPart"
+ "(Lcodechicken/multipart/TMultiPart;)V",
"codechicken$multipart$scalatraits$TSlottedTile$$super$canAddPart"
+ "(Lcodechicken/multipart/TMultiPart;)Z",
"codechicken$multipart$scalatraits$TSlottedTile$$super$clearParts()V",
"codechicken$multipart$scalatraits$TSlottedTile$$super$copyFrom"
+ "(Lcodechicken/multipart/TileMultipart;)V",
"codechicken$multipart$scalatraits$TSlottedTile$$super$partRemoved"
+ "(Lcodechicken/multipart/TMultiPart;I)V",
"copyFrom(Lcodechicken/multipart/TileMultipart;)V",
"partMap(I)Lcodechicken/multipart/TMultiPart;",
"partRemoved(Lcodechicken/multipart/TMultiPart;I)V",
"refreshPartSlots(Lcodechicken/multipart/TMultiPart;)V",
"v_partMap()[Lcodechicken/multipart/TMultiPart;",
"v_partMap_$eq([Lcodechicken/multipart/TMultiPart;)V")),
signatures);
TMultiPart[] firstMap = (TMultiPart[]) trait.getMethod("v_partMap").invoke(first);
TMultiPart[] secondMap = (TMultiPart[]) trait.getMethod("v_partMap").invoke(second);
assertEquals(27, firstMap.length);
assertEquals(27, secondMap.length);
assertNotSame(firstMap, secondMap, "Each generated tile must run the trait initializer");
assertEquals(TMultiPart[].class, first.getClass().getDeclaredField("v_partMap").getType());
TMultiPart[] replacement = new TMultiPart[27];
trait.getMethod("v_partMap_$eq", TMultiPart[].class).invoke(first, (Object) replacement);
assertSame(replacement, trait.getMethod("v_partMap").invoke(first));
}
@Test
void generatesAndCachesTileChangeTileClass() throws Exception {
int traitId = MultipartMixinFactory.getId(TTileChangeTile.class.getName().replace('.', '/'));
assertFalse(traitId < 0);
BitSet traits = new BitSet();
traits.set(traitId);
Object first = MultipartMixinFactory.construct(traits, Nil$.MODULE$);
Object second = MultipartMixinFactory.construct(traits, Nil$.MODULE$);
Class<?> trait = Class.forName("codechicken.multipart.scalatraits.TTileChangeTile");
assertTrue(first instanceof TileMultipart);
assertTrue(first instanceof TTileChangeTile);
assertTrue(trait.isInterface());
assertNotSame(first, second);
assertSame(first.getClass(), second.getClass());
assertEquals(0, trait.getDeclaredFields().length);
Set<String> signatures = new TreeSet<>();
for (java.lang.reflect.Method method : trait.getDeclaredMethods()) {
signatures.add(method.getName() + org.objectweb.asm.Type.getMethodDescriptor(method));
}
String prefix = "codechicken$multipart$scalatraits$TTileChangeTile$$super$";
assertEquals(
new TreeSet<>(
Arrays.asList(
"bindPart(Lcodechicken/multipart/TMultiPart;)V",
"clearParts()V",
"copyFrom(Lcodechicken/multipart/TileMultipart;)V",
"getWeakChanges()Z",
"onNeighborTileChange(III)V",
"partRemoved(Lcodechicken/multipart/TMultiPart;I)V",
"weakTileChanges()Z",
"weakTileChanges_$eq(Z)V",
prefix + "bindPart(Lcodechicken/multipart/TMultiPart;)V",
prefix + "clearParts()V",
prefix + "copyFrom(Lcodechicken/multipart/TileMultipart;)V",
prefix + "onNeighborTileChange(III)V",
prefix + "partRemoved(Lcodechicken/multipart/TMultiPart;I)V")),
signatures);
assertEquals(boolean.class, first.getClass().getDeclaredField("weakTileChanges").getType());
trait.getMethod("weakTileChanges_$eq", boolean.class).invoke(first, true);
assertEquals(true, trait.getMethod("weakTileChanges").invoke(first));
assertEquals(false, trait.getMethod("weakTileChanges").invoke(second), "State is per tile");
}
@Test
void generatesAndCachesFluidHandlerTileClass() throws Exception {
int traitId = MultipartMixinFactory.getId(TFluidHandlerTile.class.getName().replace('.', '/'));
assertFalse(traitId < 0);
BitSet traits = new BitSet();
traits.set(traitId);
Object first = MultipartMixinFactory.construct(traits, Nil$.MODULE$);
Object second = MultipartMixinFactory.construct(traits, Nil$.MODULE$);
Class<?> trait = Class.forName("codechicken.multipart.scalatraits.TFluidHandlerTile");
assertTrue(first instanceof TileMultipart);
assertTrue(first instanceof IFluidHandler);
assertTrue(trait.isInterface());
assertArrayEquals(new Class<?>[] { IFluidHandler.class }, trait.getInterfaces());
assertNotSame(first, second);
assertSame(first.getClass(), second.getClass());
assertEquals(0, trait.getDeclaredFields().length);
Set<String> signatures = new TreeSet<>();
for (java.lang.reflect.Method method : trait.getDeclaredMethods()) {
signatures.add(method.getName() + org.objectweb.asm.Type.getMethodDescriptor(method));
}
String prefix = "codechicken$multipart$scalatraits$TFluidHandlerTile$$super$";
assertEquals(
new TreeSet<>(
Arrays.asList(
"bindPart(Lcodechicken/multipart/TMultiPart;)V",
"canDrain(Lnet/minecraftforge/common/util/ForgeDirection;"
+ "Lnet/minecraftforge/fluids/Fluid;)Z",
"canFill(Lnet/minecraftforge/common/util/ForgeDirection;"
+ "Lnet/minecraftforge/fluids/Fluid;)Z",
"clearParts()V",
"copyFrom(Lcodechicken/multipart/TileMultipart;)V",
"drain(Lnet/minecraftforge/common/util/ForgeDirection;IZ)"
+ "Lnet/minecraftforge/fluids/FluidStack;",
"drain(Lnet/minecraftforge/common/util/ForgeDirection;"
+ "Lnet/minecraftforge/fluids/FluidStack;Z)"
+ "Lnet/minecraftforge/fluids/FluidStack;",
"fill(Lnet/minecraftforge/common/util/ForgeDirection;"
+ "Lnet/minecraftforge/fluids/FluidStack;Z)I",
"getTankInfo(Lnet/minecraftforge/common/util/ForgeDirection;)"
+ "[Lnet/minecraftforge/fluids/FluidTankInfo;",
"partRemoved(Lcodechicken/multipart/TMultiPart;I)V",
"tankList()Ljava/util/LinkedList;",
"tankList_$eq(Ljava/util/LinkedList;)V",
prefix + "bindPart(Lcodechicken/multipart/TMultiPart;)V",
prefix + "clearParts()V",
prefix + "copyFrom(Lcodechicken/multipart/TileMultipart;)V",
prefix + "partRemoved(Lcodechicken/multipart/TMultiPart;I)V")),
signatures);
assertEquals(LinkedList.class, first.getClass().getDeclaredField("tankList").getType());
LinkedList<?> firstList = (LinkedList<?>) trait.getMethod("tankList").invoke(first);
LinkedList<?> secondList = (LinkedList<?>) trait.getMethod("tankList").invoke(second);
assertNotSame(firstList, secondList, "State is per tile");
LinkedList<IFluidHandler> replacement = new LinkedList<>();
trait.getMethod("tankList_$eq", LinkedList.class).invoke(first, replacement);
assertSame(replacement, trait.getMethod("tankList").invoke(first));
}
@Test
void generatesAndCachesInventoryTileClassWithBothPublicTraitInterfaces() throws Exception {
int traitId = MultipartMixinFactory.getId(JInventoryTile.class.getName().replace('.', '/'));
assertFalse(traitId < 0);
BitSet traits = new BitSet();
traits.set(traitId);
Object first = MultipartMixinFactory.construct(traits, Nil$.MODULE$);
Object second = MultipartMixinFactory.construct(traits, Nil$.MODULE$);
Class<?> inventoryTrait = Class.forName("codechicken.multipart.scalatraits.TIInventoryTile");
Class<?> javaTrait = Class.forName("codechicken.multipart.scalatraits.JInventoryTile");
assertTrue(first instanceof TileMultipart);
assertTrue(first instanceof TIInventoryTile);
assertTrue(first instanceof ISidedInventory);
assertTrue(javaTrait.isInstance(first));
assertTrue(inventoryTrait.isInterface());
assertTrue(javaTrait.isInterface());
assertArrayEquals(new Class<?>[] { ISidedInventory.class }, inventoryTrait.getInterfaces());
assertArrayEquals(new Class<?>[] { TIInventoryTile.class }, javaTrait.getInterfaces());
assertNotSame(first, second);
assertSame(first.getClass(), second.getClass());
assertEquals(0, inventoryTrait.getDeclaredFields().length);
assertEquals(0, javaTrait.getDeclaredFields().length);
Set<String> inventorySignatures = new TreeSet<>();
for (java.lang.reflect.Method method : inventoryTrait.getDeclaredMethods()) {
inventorySignatures.add(method.getName() + org.objectweb.asm.Type.getMethodDescriptor(method));
}
String inventoryPrefix = "codechicken$multipart$scalatraits$TIInventoryTile$$super$";
assertEquals(
new TreeSet<>(
Arrays.asList(
"bindPart(Lcodechicken/multipart/TMultiPart;)V",
"canExtractItem(ILnet/minecraft/item/ItemStack;I)Z",
"canInsertItem(ILnet/minecraft/item/ItemStack;I)Z",
"clearParts()V",
"closeInventory()V",
"copyFrom(Lcodechicken/multipart/TileMultipart;)V",
"decrStackSize(II)Lnet/minecraft/item/ItemStack;",
"getAccessibleSlotsFromSide(I)[I",
"getInventoryName()Ljava/lang/String;",
"getInventoryStackLimit()I",
"getSizeInventory()I",
"getStackInSlot(I)Lnet/minecraft/item/ItemStack;",
"getStackInSlotOnClosing(I)Lnet/minecraft/item/ItemStack;",
"hasCustomInventoryName()Z",
"invList()Ljava/util/LinkedList;",
"invList_$eq(Ljava/util/LinkedList;)V",
"isItemValidForSlot(ILnet/minecraft/item/ItemStack;)Z",
"isUseableByPlayer(Lnet/minecraft/entity/player/EntityPlayer;)Z",
"openInventory()V",
"partRemoved(Lcodechicken/multipart/TMultiPart;I)V",
"rebuildSlotMap()V",
"setInventorySlotContents(ILnet/minecraft/item/ItemStack;)V",
"slotMap()[Lscala/Tuple2;",
"slotMap_$eq([Lscala/Tuple2;)V",
inventoryPrefix + "bindPart(Lcodechicken/multipart/TMultiPart;)V",
inventoryPrefix + "clearParts()V",
inventoryPrefix + "copyFrom(Lcodechicken/multipart/TileMultipart;)V",
inventoryPrefix + "partRemoved(Lcodechicken/multipart/TMultiPart;I)V")),
inventorySignatures);
Set<String> javaSignatures = new TreeSet<>();
for (java.lang.reflect.Method method : javaTrait.getDeclaredMethods()) {
javaSignatures.add(method.getName() + org.objectweb.asm.Type.getMethodDescriptor(method));
}
String javaPrefix = "codechicken$multipart$scalatraits$JInventoryTile$$";
assertEquals(
new TreeSet<>(
Arrays.asList(
"bindPart(Lcodechicken/multipart/TMultiPart;)V",
"canExtractItem(ILnet/minecraft/item/ItemStack;I)Z",
"canInsertItem(ILnet/minecraft/item/ItemStack;I)Z",
"clearParts()V",
"closeInventory()V",
"copyFrom(Lcodechicken/multipart/TileMultipart;)V",
"decrStackSize(II)Lnet/minecraft/item/ItemStack;",
"getAccessibleSlotsFromSide(I)[I",
"getInventoryName()Ljava/lang/String;",
"getInventoryStackLimit()I",
"getSizeInventory()I",
"getStackInSlot(I)Lnet/minecraft/item/ItemStack;",
"getStackInSlotOnClosing(I)Lnet/minecraft/item/ItemStack;",
"hasCustomInventoryName()Z",
"invList()Ljava/util/LinkedList;",
"invList_$eq(Ljava/util/LinkedList;)V",
"isItemValidForSlot(ILnet/minecraft/item/ItemStack;)Z",
"isUseableByPlayer(Lnet/minecraft/entity/player/EntityPlayer;)Z",
"openInventory()V",
"partRemoved(Lcodechicken/multipart/TMultiPart;I)V",
"rebuildSlotMap()V",
"refreshInventorySlots()V",
"setInventorySlotContents(ILnet/minecraft/item/ItemStack;)V",
"slotMap()[Lscala/Tuple2;",
"slotMap_$eq([Lscala/Tuple2;)V",
javaPrefix + "invList()Ljava/util/LinkedList;",
javaPrefix + "invList_$eq(Ljava/util/LinkedList;)V",
javaPrefix + "slotMap()[Lscala/Tuple2;",
javaPrefix + "slotMap_$eq([Lscala/Tuple2;)V",
inventoryPrefix + "bindPart(Lcodechicken/multipart/TMultiPart;)V",
inventoryPrefix + "clearParts()V",
inventoryPrefix + "copyFrom(Lcodechicken/multipart/TileMultipart;)V",
inventoryPrefix + "partRemoved(Lcodechicken/multipart/TMultiPart;I)V",
javaPrefix + "super$bindPart(Lcodechicken/multipart/TMultiPart;)V",
javaPrefix + "super$clearParts()V",
javaPrefix + "super$copyFrom(Lcodechicken/multipart/TileMultipart;)V",
javaPrefix + "super$partRemoved(Lcodechicken/multipart/TMultiPart;I)V")),
javaSignatures);
String fieldPrefix = "codechicken$multipart$scalatraits$JInventoryTile$$";
java.lang.reflect.Field listField = first.getClass().getDeclaredField(fieldPrefix + "invList");
java.lang.reflect.Field mapField = first.getClass().getDeclaredField(fieldPrefix + "slotMap");
assertEquals(LinkedList.class, listField.getType());
assertEquals(scala.Tuple2[].class, mapField.getType());
assertTrue(Modifier.isPrivate(listField.getModifiers()));
assertTrue(Modifier.isPrivate(mapField.getModifiers()));
LinkedList<?> firstList = (LinkedList<?>) javaTrait.getMethod("invList").invoke(first);
LinkedList<?> secondList = (LinkedList<?>) javaTrait.getMethod("invList").invoke(second);
Object[] firstMap = (Object[]) javaTrait.getMethod("slotMap").invoke(first);
Object[] secondMap = (Object[]) javaTrait.getMethod("slotMap").invoke(second);
assertTrue(firstList.isEmpty());
assertEquals(0, firstMap.length);
assertNotSame(firstList, secondList, "Each generated tile must initialize its inventory list");
assertNotSame(firstMap, secondMap, "Each generated tile must initialize its slot map");
LinkedList<IInventory> replacementList = new LinkedList<>();
scala.Tuple2<?, ?>[] replacementMap = new scala.Tuple2[0];
javaTrait.getMethod("invList_$eq", LinkedList.class).invoke(first, replacementList);
javaTrait.getMethod("slotMap_$eq", scala.Tuple2[].class).invoke(first, (Object) replacementMap);
assertSame(replacementList, javaTrait.getMethod("invList").invoke(first));
assertSame(replacementMap, javaTrait.getMethod("slotMap").invoke(first));
}
@Test
void generatesClientAndRandomDisplayTickTraitsWithTheirExactHierarchy() throws Exception {
int clientTraitId = MultipartMixinFactory.getId(TileMultipartClient.class.getName().replace('.', '/'));
int randomTraitId = MultipartMixinFactory.getId(TRandomDisplayTickTile.class.getName().replace('.', '/'));
assertFalse(clientTraitId < 0);
assertFalse(randomTraitId < 0);
BitSet clientTraits = new BitSet();
clientTraits.set(clientTraitId);
Object first = MultipartMixinFactory.construct(clientTraits, Nil$.MODULE$);
Object second = MultipartMixinFactory.construct(clientTraits, Nil$.MODULE$);
BitSet randomTraits = (BitSet) clientTraits.clone();
randomTraits.set(randomTraitId);
Object randomTile = MultipartMixinFactory.construct(randomTraits, Nil$.MODULE$);
Class<?> clientTrait = Class.forName("codechicken.multipart.TileMultipartClient");
Class<?> randomTrait = Class.forName("codechicken.multipart.scalatraits.TRandomDisplayTickTile");
assertTrue(first instanceof TileMultipart);
assertTrue(first instanceof TileMultipartClient);
assertTrue(randomTile instanceof TileMultipartClient);
assertTrue(randomTile instanceof TRandomDisplayTickTile);
assertTrue(clientTrait.isInterface());
assertTrue(randomTrait.isInterface());
assertEquals(0, clientTrait.getInterfaces().length);
assertArrayEquals(new Class<?>[] { TileMultipartClient.class }, randomTrait.getInterfaces());
assertNotSame(first, second);
assertSame(first.getClass(), second.getClass());
assertNotSame(first.getClass(), randomTile.getClass());
assertEquals(0, clientTrait.getDeclaredFields().length);
assertEquals(0, randomTrait.getDeclaredFields().length);
org.objectweb.asm.tree.ClassNode clientNode = codechicken.multipart.asm.ASMMixinCompiler$.MODULE$
.classNode("codechicken/multipart/TileMultipartClient");
org.objectweb.asm.tree.ClassNode randomNode = codechicken.multipart.asm.ASMMixinCompiler$.MODULE$
.classNode("codechicken/multipart/scalatraits/TRandomDisplayTickTile");
assertTrue((clientNode.access & org.objectweb.asm.Opcodes.ACC_INTERFACE) != 0);
assertTrue((randomNode.access & org.objectweb.asm.Opcodes.ACC_INTERFACE) != 0);
assertEquals(Collections.emptyList(), clientNode.interfaces);
assertEquals(Collections.singletonList("codechicken/multipart/TileMultipartClient"), randomNode.interfaces);
assertEquals(0, clientNode.fields.size());
assertEquals(0, randomNode.fields.size());
Set<String> clientSignatures = new TreeSet<>();
for (org.objectweb.asm.tree.MethodNode method : clientNode.methods) {
clientSignatures.add(method.name + method.desc);
}
String prefix = "codechicken$multipart$TileMultipartClient$$";
assertEquals(
new TreeSet<>(
Arrays.asList(
prefix + "cachedRenderBounds()Lnet/minecraft/util/AxisAlignedBB;",
prefix + "cachedRenderBounds_$eq(Lnet/minecraft/util/AxisAlignedBB;)V",
prefix + "dynamicCache()[Lcodechicken/multipart/TMultiPart;",
prefix + "dynamicCache_$eq([Lcodechicken/multipart/TMultiPart;)V",
prefix + "staticCache()[Lcodechicken/multipart/TMultiPart;",
prefix + "staticCache_$eq([Lcodechicken/multipart/TMultiPart;)V",
prefix + "super$markRender()V",
"getRenderBoundingBox()Lnet/minecraft/util/AxisAlignedBB;",
"hasDynamicParts()Z",
"hasDynamicParts_$eq(Z)V",
"markRender()V",
"randomDisplayTick(Ljava/util/Random;)V",
"renderDynamic(Lcodechicken/lib/vec/Vector3;FI)V",
"renderStatic(Lnet/minecraft/world/IBlockAccess;Lcodechicken/lib/vec/Vector3;"
+ "Lnet/minecraft/client/renderer/RenderBlocks;)Z",
"shouldRenderInPass(I)Z",
"updateRenderCache()V")),
clientSignatures);
Set<String> randomSignatures = new TreeSet<>();
for (org.objectweb.asm.tree.MethodNode method : randomNode.methods) {
randomSignatures.add(method.name + method.desc);
}
assertEquals(new TreeSet<>(Arrays.asList("randomDisplayTick(Ljava/util/Random;)V")), randomSignatures);
assertGeneratedField(first, prefix + "cachedRenderBounds", net.minecraft.util.AxisAlignedBB.class);
assertGeneratedField(first, prefix + "staticCache", TMultiPart[].class);
assertGeneratedField(first, prefix + "dynamicCache", TMultiPart[].class);
assertGeneratedField(first, "hasDynamicParts", boolean.class);
}
private static void assertGeneratedField(Object tile, String name, Class<?> type) throws Exception {
java.lang.reflect.Field field = tile.getClass().getDeclaredField(name);
assertEquals(type, field.getType());
assertTrue(Modifier.isPrivate(field.getModifiers()));
}
@Test
void generatedJavaTraitOverridesPartialOcclusion() throws Exception {
PartialPart existing = new PartialPart(voxel(0));
TileMultipart tile = MultipartHelper.createTileFromParts(Collections.singletonList(existing));
TileMultipart second = MultipartHelper
.createTileFromParts(Collections.singletonList(new PartialPart(voxel(2))));
Class<?> trait = Class.forName("codechicken.multipart.scalatraits.TPartialOcclusionTile");
assertTrue(trait.isInterface(), "The registered Java mixin class is rewritten to a trait interface");
assertTrue(trait.isInstance(tile));
assertSame(tile.getClass(), second.getClass(), "The Java trait combination must keep using the class cache");
assertEquals(0, trait.getDeclaredFields().length);
Set<String> signatures = new TreeSet<>();
for (java.lang.reflect.Method method : trait.getDeclaredMethods()) {
signatures.add(method.getName() + org.objectweb.asm.Type.getMethodDescriptor(method));
}
assertEquals(
new TreeSet<>(
Arrays.asList(
"codechicken$multipart$scalatraits$TPartialOcclusionTile$$super$occlusionTest"
+ "(Lscala/collection/Seq;Lcodechicken/multipart/TMultiPart;)Z",
"occlusionTest(Lscala/collection/Seq;Lcodechicken/multipart/TMultiPart;)Z",
"partialOcclusionTest(Lscala/collection/Seq;)Z")),
signatures);
assertEquals(
boolean.class,
tile.getClass().getMethod("partialOcclusionTest", scala.collection.Seq.class).getReturnType());
assertTrue(tile.canAddPart(new PartialPart(voxel(1))));
assertFalse(tile.canAddPart(new PartialPart(voxel(0))));
assertTrue(tile.occlusionTest(tile.partList(), new PartialPart(voxel(1))));
assertFalse(tile.occlusionTest(tile.partList(), new PartialPart(voxel(0))));
}
@Test
void javaOcclusionQueryDispatchesThroughTheGeneratedPartialTrait() {
PartialPart existing = new PartialPart(voxel(0));
PartialPart overlapping = new PartialPart(voxel(0));
PartialPart disjoint = new PartialPart(voxel(1));
TileMultipart tile = MultipartHelper.createTileFromParts(Collections.singletonList(existing));
assertTrue(
new TileMultipart().testOcclusion(Collections.singletonList(existing), overlapping),
"Pair tests alone allow these parts; the generated aggregate check must reject them");
assertFalse(tile.testOcclusion(Collections.singletonList(existing), overlapping));
assertTrue(tile.testOcclusion(Collections.singletonList(existing), disjoint));
assertEquals(Collections.singletonList(existing), tile.jPartList());
assertSame(tile, existing.tile());
assertNull(overlapping.tile());
assertNull(disjoint.tile());
}
@Test
void generatedServerPassThroughDelegatesCopiesAndAllowsOnlyOneImplementor() throws Exception {
PassThroughPart part = new PassThroughPart();
TileMultipart tile = MultipartHelper.createTileFromParts(Collections.singletonList(part));
assertTrue(tile instanceof GeneratorPassThroughFixture);
GeneratorPassThroughFixture api = (GeneratorPassThroughFixture) tile;
assertEquals(12, api.transform(5));
assertEquals("part:value", api.transform("value"));
assertSame(part, api.implementation());
assertFalse(tile.canAddPart(new PassThroughPart()));
TileMultipart copy = (TileMultipart) tile.getClass().getDeclaredConstructor().newInstance();
copy.from(tile);
assertSame(part, ((GeneratorPassThroughFixture) copy).implementation());
assertSame(copy, part.tile());
copy.partRemoved(part, 0);
assertTrue(copy.canAddPart(new PassThroughPart()), "Removing the delegate must clear the generated impl field");
}
private static Cuboid6 voxel(int x) {
return new Cuboid6(x / 8d, 0, 0, (x + 1) / 8d, 1 / 8d, 1 / 8d);
}
private static final class PartialPart extends TMultiPart implements JPartialOcclusion {
private final Cuboid6 box;
private PartialPart(Cuboid6 box) {
this.box = box;
}
@Override
public String getType() {
return "partial_fixture";
}
@Override
public Iterable<Cuboid6> getPartialOcclusionBoxes() {
return Collections.singletonList(box);
}
}
private static final class PassThroughPart extends TMultiPart implements GeneratorPassThroughFixture {
@Override
public String getType() {
return "pass_through_fixture";
}
@Override
public int transform(int value) {
return value + 7;
}
@Override
public String transform(String value) {
return "part:" + value;
}
@Override
public TMultiPart implementation() {
return this;
}
}
}
@@ -0,0 +1,136 @@
package codechicken.multipart.test;
import java.io.File;
import java.io.PrintWriter;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.LauncherDiscoveryRequest;
import org.junit.platform.launcher.LauncherSession;
import org.junit.platform.launcher.TestPlan;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.junit.platform.launcher.listeners.SummaryGeneratingListener;
import org.junit.platform.launcher.listeners.TestExecutionSummary;
import org.junit.platform.reporting.legacy.xml.LegacyXmlReportGeneratingListener;
import codechicken.microblock.MicroblockGenerator;
import codechicken.multipart.MultipartGenerator;
import codechicken.multipart.examples.BlockConversionExample;
import codechicken.multipart.examples.CustomTileTraitExample;
import codechicken.multipart.examples.IlluminatedMicroblockExample;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerAboutToStartEvent;
import cpw.mods.fml.common.event.FMLServerStartedEvent;
import cpw.mods.fml.common.registry.GameRegistry;
@Mod(
modid = "ForgeMultipartTests",
name = "ForgeMultipart Functional Tests",
version = "1.0",
dependencies = "required-after:ForgeMultipart",
acceptableRemoteVersions = "*")
public final class ForgeMultipartFunctionalTestMod {
static boolean preInitialized;
static boolean initialized;
static boolean postInitialized;
static boolean serverAboutToStart;
static boolean serverStarted;
static int externalScalaMicroblockTraitId;
static Block illuminatedLamp;
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event) {
illuminatedLamp = new Block(Material.glass) {};
GameRegistry.registerBlock(illuminatedLamp, "illuminated_lamp");
preInitialized = true;
}
@Mod.EventHandler
public void init(FMLInitializationEvent event) {
PartRegistrationFunctionalTest.registerDuringInit();
MultipartGenerator.registerPassThroughInterface(GeneratorPassThroughFixture.class.getName(), false, true);
CustomTileTraitExample.register();
externalScalaMicroblockTraitId = MicroblockGenerator
.registerTrait("codechicken.multipart.test.ExternalScalaMicroblockFixture");
IlluminatedMicroblockExample.registerMaterials(illuminatedLamp);
BlockConversionExample.register(illuminatedLamp);
initialized = true;
}
@Mod.EventHandler
public void postInit(FMLPostInitializationEvent event) {
postInitialized = true;
}
@Mod.EventHandler
public void serverAboutToStart(FMLServerAboutToStartEvent event) {
serverAboutToStart = true;
}
@Mod.EventHandler
public void serverStarted(FMLServerStartedEvent event) {
serverStarted = true;
MinecraftServer server = MinecraftServer.getServer();
server.addChatMessage(new ChatComponentText("Running ForgeMultipart functional tests..."));
if (Boolean.getBoolean("forgemultipart.profileFunctionalTests")) {
ForgeMultipartProfileWorkload.run();
}
TestExecutionSummary summary = runTests();
if (summary.getTestsFoundCount() == 0) {
throw new IllegalStateException("No ForgeMultipart functional tests were discovered");
}
if (summary.getTotalFailureCount() > 0) {
throw new IllegalStateException(
"ForgeMultipart functional tests failed; check junit-out and the server log");
}
server.addChatMessage(new ChatComponentText("ForgeMultipart functional tests passed"));
server.initiateShutdown();
}
private static TestExecutionSummary runTests() {
System.setProperty("junit.platform.reporting.open.xml.enabled", "false");
Path reportDirectory = FileSystems.getDefault().getPath("./junit-out/").toAbsolutePath();
File reportDirectoryFile = reportDirectory.toFile();
reportDirectoryFile.mkdirs();
File[] oldReports = reportDirectoryFile.listFiles((directory, name) -> name.endsWith(".xml"));
if (oldReports != null) {
for (File oldReport : oldReports) {
oldReport.delete();
}
}
LauncherDiscoveryRequest discovery = LauncherDiscoveryRequestBuilder.request()
.selectors(DiscoverySelectors.selectPackage("codechicken.multipart.test")).build();
SummaryGeneratingListener summaryListener = new SummaryGeneratingListener();
PrintWriter stderr = new PrintWriter(System.err, true);
LegacyXmlReportGeneratingListener xmlListener = new LegacyXmlReportGeneratingListener(reportDirectory, stderr);
try (LauncherSession session = LauncherFactory.openSession()) {
Launcher launcher = session.getLauncher();
TestPlan plan = launcher.discover(discovery);
launcher.registerTestExecutionListeners(summaryListener, xmlListener);
launcher.execute(plan);
}
TestExecutionSummary summary = summaryListener.getSummary();
summary.printFailuresTo(stderr, 32);
summary.printTo(stderr);
stderr.flush();
return summary;
}
}
@@ -0,0 +1,323 @@
package codechicken.multipart.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import net.minecraft.block.Block;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraftforge.common.util.ForgeDirection;
import codechicken.multipart.BlockMultipart;
import codechicken.multipart.IRedstonePart;
import codechicken.multipart.IRedstoneTile;
import codechicken.multipart.MultipartHelper;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TileMultipart;
import scala.runtime.AbstractFunction1;
import scala.runtime.BoxedUnit;
/** Fixed workload used only by the opt-in JFR baseline run. */
final class ForgeMultipartProfileWorkload {
private static final int PART_COUNT = 8;
private static final int WARMUP_ITERATIONS = 1_000_000;
private static final int PROFILE_ITERATIONS = 50_000_000;
private static volatile long sink;
private ForgeMultipartProfileWorkload() {}
static void run() {
List<TMultiPart> tickingParts = new ArrayList<>();
for (int i = 0; i < PART_COUNT; i++) {
tickingParts.add(new ProfilePart());
}
TileMultipart tickingTile = MultipartHelper.createTileFromParts(tickingParts);
ProfileBlockAccess blockAccess = new ProfileBlockAccess(tickingTile);
List<TMultiPart> redstoneParts = new ArrayList<>();
for (int i = 0; i < PART_COUNT; i++) {
redstoneParts.add(new RedstoneProfilePart(i));
}
TileMultipart redstoneTile = MultipartHelper.createTileFromParts(redstoneParts);
IRedstoneTile redstone = (IRedstoneTile) redstoneTile;
CountingFunction operation = new CountingFunction();
com.sun.management.ThreadMXBean allocationBean = allocationBean();
long threadId = Thread.currentThread().getId();
profileUpdateEntity(tickingTile, WARMUP_ITERATIONS);
profileOperate(tickingTile, operation, WARMUP_ITERATIONS);
profileLightValue(tickingTile, WARMUP_ITERATIONS);
profileGetTile(blockAccess, WARMUP_ITERATIONS);
profileRedstone(redstoneTile, redstone, WARMUP_ITERATIONS);
long updateStartMillis = System.currentTimeMillis();
long updateStartBytes = allocationBean.getThreadAllocatedBytes(threadId);
long updateStart = System.nanoTime();
profileUpdateEntity(tickingTile, PROFILE_ITERATIONS);
long updateNanos = System.nanoTime() - updateStart;
long updateBytes = allocationBean.getThreadAllocatedBytes(threadId) - updateStartBytes;
long operateStartMillis = System.currentTimeMillis();
long operateStartBytes = allocationBean.getThreadAllocatedBytes(threadId);
long operateStart = System.nanoTime();
profileOperate(tickingTile, operation, PROFILE_ITERATIONS);
long operateNanos = System.nanoTime() - operateStart;
long operateBytes = allocationBean.getThreadAllocatedBytes(threadId) - operateStartBytes;
long lightStartMillis = System.currentTimeMillis();
long lightStartBytes = allocationBean.getThreadAllocatedBytes(threadId);
long lightStart = System.nanoTime();
long lightChecksum = profileLightValue(tickingTile, PROFILE_ITERATIONS);
long lightNanos = System.nanoTime() - lightStart;
long lightBytes = allocationBean.getThreadAllocatedBytes(threadId) - lightStartBytes;
long getTileStartMillis = System.currentTimeMillis();
long getTileStartBytes = allocationBean.getThreadAllocatedBytes(threadId);
long getTileStart = System.nanoTime();
long getTileChecksum = profileGetTile(blockAccess, PROFILE_ITERATIONS);
long getTileNanos = System.nanoTime() - getTileStart;
long getTileBytes = allocationBean.getThreadAllocatedBytes(threadId) - getTileStartBytes;
long redstoneStartMillis = System.currentTimeMillis();
long redstoneStartBytes = allocationBean.getThreadAllocatedBytes(threadId);
long redstoneStart = System.nanoTime();
long redstoneChecksum = profileRedstone(redstoneTile, redstone, PROFILE_ITERATIONS);
long redstoneNanos = System.nanoTime() - redstoneStart;
long redstoneBytes = allocationBean.getThreadAllocatedBytes(threadId) - redstoneStartBytes;
long updateChecksum = 0;
for (TMultiPart part : tickingParts) {
updateChecksum += ((ProfilePart) part).updates;
}
sink = updateChecksum + operation.applications + lightChecksum + getTileChecksum + redstoneChecksum;
writeResults(
updateStartMillis,
updateNanos,
updateBytes,
operateStartMillis,
operateNanos,
operateBytes,
lightStartMillis,
lightNanos,
lightBytes,
getTileStartMillis,
getTileNanos,
getTileBytes,
redstoneStartMillis,
redstoneNanos,
redstoneBytes,
sink);
}
private static void profileUpdateEntity(TileMultipart tile, int iterations) {
for (int i = 0; i < iterations; i++) {
tile.updateEntity();
}
}
private static void profileOperate(TileMultipart tile, CountingFunction operation, int iterations) {
for (int i = 0; i < iterations; i++) {
tile.operate(operation);
}
}
private static long profileLightValue(TileMultipart tile, int iterations) {
long checksum = 0;
for (int i = 0; i < iterations; i++) {
checksum += tile.getLightValue();
}
return checksum;
}
private static long profileGetTile(IBlockAccess world, int iterations) {
long checksum = 0;
for (int i = 0; i < iterations; i++) {
if (BlockMultipart.getTile(world, 0, 0, 0) != null) {
checksum++;
}
}
return checksum;
}
private static long profileRedstone(TileMultipart tile, IRedstoneTile redstone, int iterations) {
long checksum = 0;
for (int i = 0; i < iterations; i++) {
int side = i % 6;
checksum += tile.strongPowerLevel(side);
checksum += redstone.getConnectionMask(side);
checksum += redstone.weakPowerLevel(side, 0x1F);
}
return checksum;
}
private static void writeResults(long updateStartMillis, long updateNanos, long updateBytes,
long operateStartMillis, long operateNanos, long operateBytes, long lightStartMillis, long lightNanos,
long lightBytes, long getTileStartMillis, long getTileNanos, long getTileBytes, long redstoneStartMillis,
long redstoneNanos, long redstoneBytes, long checksum) {
File output = new File("forgemultipart-profile.txt");
try (PrintWriter writer = new PrintWriter(output)) {
writer.printf(Locale.ROOT, "java=%s%n", System.getProperty("java.runtime.version"));
writer.printf(Locale.ROOT, "parts=%d%n", PART_COUNT);
writer.printf(Locale.ROOT, "warmupIterations=%d%n", WARMUP_ITERATIONS);
writer.printf(Locale.ROOT, "profileIterations=%d%n", PROFILE_ITERATIONS);
writeTiming(writer, "updateEntity", updateStartMillis, updateNanos, updateBytes);
writeTiming(writer, "operate", operateStartMillis, operateNanos, operateBytes);
writeTiming(writer, "lightValue", lightStartMillis, lightNanos, lightBytes);
writeTiming(writer, "getTile", getTileStartMillis, getTileNanos, getTileBytes);
writeTiming(writer, "redstoneQueries", redstoneStartMillis, redstoneNanos, redstoneBytes);
writer.printf(Locale.ROOT, "checksum=%d%n", checksum);
} catch (FileNotFoundException e) {
throw new IllegalStateException("Could not write ForgeMultipart profile results", e);
}
}
private static void writeTiming(PrintWriter writer, String name, long startMillis, long nanos,
long allocatedBytes) {
double seconds = nanos / 1_000_000_000d;
writer.printf(Locale.ROOT, "%s.startEpochMillis=%d%n", name, startMillis);
writer.printf(Locale.ROOT, "%s.nanos=%d%n", name, nanos);
writer.printf(Locale.ROOT, "%s.operationsPerSecond=%.0f%n", name, PROFILE_ITERATIONS / seconds);
writer.printf(Locale.ROOT, "%s.allocatedBytes=%d%n", name, allocatedBytes);
writer.printf(
Locale.ROOT,
"%s.allocatedBytesPerOperation=%.1f%n",
name,
allocatedBytes / (double) PROFILE_ITERATIONS);
}
private static com.sun.management.ThreadMXBean allocationBean() {
java.lang.management.ThreadMXBean bean = ManagementFactory.getThreadMXBean();
if (!(bean instanceof com.sun.management.ThreadMXBean)) {
throw new IllegalStateException("The profiling JVM does not expose thread allocation counters");
}
com.sun.management.ThreadMXBean allocationBean = (com.sun.management.ThreadMXBean) bean;
if (!allocationBean.isThreadAllocatedMemorySupported()) {
throw new IllegalStateException("The profiling JVM does not support thread allocation counters");
}
if (!allocationBean.isThreadAllocatedMemoryEnabled()) {
allocationBean.setThreadAllocatedMemoryEnabled(true);
}
return allocationBean;
}
private static class ProfilePart extends TMultiPart {
private int updates;
@Override
public String getType() {
return "profile_part";
}
@Override
public boolean doesTick() {
return true;
}
@Override
public void update() {
updates++;
}
}
private static final class RedstoneProfilePart extends ProfilePart implements IRedstonePart {
private final int power;
private RedstoneProfilePart(int power) {
this.power = power;
}
@Override
public int strongPowerLevel(int side) {
return power + side;
}
@Override
public int weakPowerLevel(int side) {
return power + side;
}
@Override
public boolean canConnectRedstone(int side) {
return true;
}
}
private static final class CountingFunction extends AbstractFunction1<TMultiPart, BoxedUnit> {
private long applications;
@Override
public BoxedUnit apply(TMultiPart part) {
applications++;
return BoxedUnit.UNIT;
}
}
private static final class ProfileBlockAccess implements IBlockAccess {
private final TileEntity tile;
private ProfileBlockAccess(TileEntity tile) {
this.tile = tile;
}
@Override
public Block getBlock(int x, int y, int z) {
return null;
}
@Override
public TileEntity getTileEntity(int x, int y, int z) {
return tile;
}
@Override
public int getLightBrightnessForSkyBlocks(int x, int y, int z, int minimum) {
return 0;
}
@Override
public int getBlockMetadata(int x, int y, int z) {
return 0;
}
@Override
public int isBlockProvidingPowerTo(int x, int y, int z, int direction) {
return 0;
}
@Override
public boolean isAirBlock(int x, int y, int z) {
return false;
}
@Override
public BiomeGenBase getBiomeGenForCoords(int x, int z) {
return null;
}
@Override
public int getHeight() {
return 0;
}
@Override
public boolean extendedLevelsInChunkCache() {
return false;
}
@Override
public boolean isSideSolid(int x, int y, int z, ForgeDirection side, boolean defaultValue) {
return defaultValue;
}
}
}
@@ -0,0 +1,13 @@
package codechicken.multipart.test;
import codechicken.multipart.TMultiPart;
/** Representative external tile API for generated pass-through characterization. */
public interface GeneratorPassThroughFixture {
int transform(int value);
String transform(String value);
TMultiPart implementation();
}
@@ -0,0 +1,63 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;
import net.minecraft.init.Blocks;
import org.junit.jupiter.api.Test;
import codechicken.microblock.GrassMicroMaterial;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.TopMicroMaterial;
import codechicken.microblock.TopMicroMaterial$;
class GrassMicroMaterialFunctionalTest {
@Test
void dedicatedServerKeepsTheCommonRenderingSurfaceAndRegisteredMaterials() throws Exception {
GrassMicroMaterial grass = (GrassMicroMaterial) MicroMaterialRegistry.getMaterial("minecraft:grass");
TopMicroMaterial mycelium = (TopMicroMaterial) MicroMaterialRegistry.getMaterial("minecraft:mycelium");
assertSame(Blocks.grass, grass.block());
assertEquals(0, grass.meta());
assertEquals("minecraft:grass", grass.blockKey());
assertSame(Blocks.mycelium, mycelium.block());
assertEquals(0, mycelium.meta());
assertEquals("minecraft:mycelium", mycelium.blockKey());
assertEquals(
new TreeSet<>(Arrays.asList("loadIcons", "renderMicroFace", "sideIconT", "sideIconT_$eq")),
publicDeclaredMethodNames(GrassMicroMaterial.class));
assertEquals(
new TreeSet<>(Arrays.asList("$lessinit$greater$default$2", "renderMicroFace")),
publicDeclaredMethodNames(TopMicroMaterial.class));
assertEquals(
new TreeSet<>(Arrays.asList("$lessinit$greater$default$2")),
publicDeclaredMethodNames(TopMicroMaterial$.class));
Field overlay = GrassMicroMaterial.class.getDeclaredField("sideIconT");
assertFalse(Modifier.isStatic(overlay.getModifiers()));
assertSame(TopMicroMaterial$.MODULE$, TopMicroMaterial$.class.getField("MODULE$").get(null));
assertEquals(0, TopMicroMaterial.$lessinit$greater$default$2());
assertTrue(TopMicroMaterial.class.isInstance(mycelium));
}
private static Set<String> publicDeclaredMethodNames(Class<?> type) {
Set<String> names = new TreeSet<>();
for (Method method : type.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers())) {
names.add(method.getName());
}
}
return names;
}
}
@@ -0,0 +1,308 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.List;
import net.minecraft.util.IIcon;
import org.junit.jupiter.api.Test;
import codechicken.lib.data.MCDataInput;
import codechicken.lib.raytracer.IndexedCuboid6;
import codechicken.lib.vec.Cuboid6;
import codechicken.lib.vec.Vector3;
import codechicken.microblock.HollowMicroClass$;
import codechicken.microblock.HollowMicroblock$class;
import codechicken.microblock.HollowMicroblockClient;
import codechicken.microblock.HollowMicroblockClient$class;
import codechicken.microblock.ISidedHollowConnect;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.MicroMaterialRegistry.IMicroMaterial;
import codechicken.microblock.Microblock;
import codechicken.microblock.TMicroOcclusionClient$class;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TileMultipart;
import scala.Function5;
import scala.runtime.AbstractFunction5;
import scala.runtime.BoxedUnit;
class HollowMicroblockClientFunctionalTest {
@Test
void realBoundsAndLiveCenterConnectorDriveClientMaskAndRimsOnAllFortyTwoShapes() {
ClientProbe part = new ClientProbe(MicroMaterialRegistry.materialID("minecraft:stone"));
SlotTile tile = new SlotTile();
part.bind(tile);
for (int size = 1; size <= 7; size++) {
for (int side = 0; side < 6; side++) {
part.setShape(size, side);
for (int opening : new int[] { 1, 8, 11 }) {
tile.connector.size = opening;
part.recalcBounds();
assertEquals(opening << 8, part.renderMask());
assertEquals(side, tile.connector.side);
Cuboid6 physical = part.getBounds();
assertNotSame(physical, part.renderBounds());
assertBounds(physical, part.renderBounds());
int[] calls = { 0 };
double[] volume = { 0 };
part.renderHollow(
new Vector3(),
0,
part.renderBounds(),
0,
false,
new AbstractFunction5<Vector3, IMicroMaterial, Object, Cuboid6, Object, BoxedUnit>() {
@Override
public BoxedUnit apply(Vector3 pos, IMicroMaterial material, Object pass, Cuboid6 box,
Object mask) {
assertSame(part.getIMaterial(), material);
assertEquals(0, pass);
// The first two callbacks draw internal walls; the last four span the rim volume.
if (calls[0]++ >= 2) volume[0] += (box.max.x - box.min.x) * (box.max.y - box.min.y)
* (box.max.z - box.min.z);
return BoxedUnit.UNIT;
}
});
assertEquals(6, calls[0]);
assertEquals(size / 8D * (1 - opening / 16D * (opening / 16D)), volume[0], 1e-12);
}
tile.connected = false;
part.recalcBounds();
assertEquals(8 << 8, part.renderMask());
tile.connected = true;
}
}
}
@Test
void occlusionClientRefreshesClippingAndMasksWithLiveStoneAndGlassNeighbors() {
int stone = MicroMaterialRegistry.materialID("minecraft:stone");
int glass = MicroMaterialRegistry.materialID("minecraft:glass");
assertNotEquals(stone, glass);
ClientProbe part = new ClientProbe(stone);
ClientProbe neighbor = new ClientProbe(stone);
SlotTile tile = new SlotTile();
part.bind(tile);
tile.connector.size = 8;
part.setShape(2, 4);
neighbor.setShape(1, 0);
tile.neighbor = neighbor;
TMicroOcclusionClient$class.recalcBounds(part);
assertEquals(1, part.renderMask());
assertEquals(0, part.renderBounds().min.y);
Cuboid6 original = part.getBounds().copy();
neighbor.setShape(4, 0);
part.recalcBounds();
assertEquals(8 << 8, part.renderMask());
assertEquals(0.5, part.renderBounds().min.y);
assertBounds(original, part.getBounds());
neighbor.material_$eq(glass);
TMicroOcclusionClient$class.recalcBounds(part);
assertEquals(0, part.renderMask());
assertBounds(original, part.renderBounds());
part.material_$eq(glass);
neighbor.material_$eq(stone);
neighbor.setShape(1, 0);
TMicroOcclusionClient$class.recalcBounds(part);
assertEquals(0.125, part.renderBounds().min.y);
assertEquals(0, part.renderMask());
tile.neighbor = null;
TMicroOcclusionClient$class.recalcBounds(part);
assertNotSame(part.getBounds(), part.renderBounds());
assertBounds(original, part.renderBounds());
assertEquals(0, part.renderMask());
}
private static void assertBounds(Cuboid6 expected, Cuboid6 actual) {
assertArrayEquals(
new double[] { expected.min.x, expected.min.y, expected.min.z, expected.max.x, expected.max.y,
expected.max.z },
new double[] { actual.min.x, actual.min.y, actual.min.z, actual.max.x, actual.max.y, actual.max.z },
1e-12);
}
private static final class Connector extends TMultiPart implements ISidedHollowConnect {
int size;
int side;
@Override
public String getType() {
return "test:hollow_connector";
}
@Override
public int getHollowSize(int side) {
this.side = side;
return size;
}
}
private static final class SlotTile extends TileMultipart {
final Connector connector = new Connector();
boolean connected = true;
TMultiPart neighbor;
@Override
public TMultiPart partMap(int slot) {
return slot == 0 ? neighbor : slot == 6 && connected ? connector : null;
}
}
/** Uses client helpers with real Forge factories; the dedicated server strips client factory creation. */
private static final class ClientProbe extends Microblock implements HollowMicroblockClient {
Cuboid6 bounds;
int mask;
ClientProbe(int material) {
super(material);
HollowMicroblockClient$class.$init$(this);
}
@Override
public HollowMicroClass$ microClass() {
return HollowMicroClass$.MODULE$;
}
@Override
public int itemClassID() {
return microClass().getClassId();
}
@Override
public int redstoneConductionMap() {
return HollowMicroblock$class.redstoneConductionMap(this);
}
@Override
public int getSlotMask() {
return 1 << getSlot();
}
@Override
public boolean edgeCornerOcclusionTest(codechicken.microblock.TMicroOcclusion edge,
codechicken.microblock.TMicroOcclusion corner) {
return codechicken.microblock.TMicroOcclusion$class.edgeCornerOcclusionTest(this, edge, corner);
}
@Override
public List<Cuboid6> getCollisionBoxes() {
return HollowMicroblock$class.getCollisionBoxes(this);
}
@Override
public List<IndexedCuboid6> getSubParts() {
return HollowMicroblock$class.getSubParts(this);
}
@Override
public Cuboid6 getBounds() {
return HollowMicroblock$class.getBounds(this);
}
@Override
public int getSlot() {
return getShape();
}
@Override
public int getHollowSize() {
return HollowMicroblock$class.getHollowSize(this);
}
@Override
public List<Cuboid6> getPartialOcclusionBoxes() {
return HollowMicroblock$class.getPartialOcclusionBoxes(this);
}
@Override
public Iterable<Cuboid6> getOcclusionBoxes() {
return HollowMicroblock$class.getOcclusionBoxes(this);
}
@Override
public boolean allowCompleteOcclusion() {
return true;
}
@Override
public boolean solid(int side) {
return false;
}
@Override
public Cuboid6 renderBounds() {
return bounds;
}
@Override
public void renderBounds_$eq(Cuboid6 value) {
bounds = value;
}
@Override
public int renderMask() {
return mask;
}
@Override
public void renderMask_$eq(int value) {
mask = value;
}
@Override
public int getPriorityClass() {
return 0;
}
@Override
public IIcon getBrokenIcon(int side) {
throw new AssertionError("icon lookup");
}
@Override
public void recalcBounds() {
HollowMicroblockClient$class.recalcBounds(this);
}
@Override
public void render(Vector3 pos, int pass) {
HollowMicroblockClient$class.render(this, pos, pass);
}
@Override
public void renderHollow(Vector3 pos, int pass, Cuboid6 c, int sideMask, boolean face,
Function5<Vector3, IMicroMaterial, Object, Cuboid6, Object, BoxedUnit> f) {
HollowMicroblockClient$class.renderHollow(this, pos, pass, c, sideMask, face, f);
}
public void codechicken$microblock$HollowMicroblockClient$$super$recalcBounds() {
TMicroOcclusionClient$class.recalcBounds(this);
}
public boolean codechicken$microblock$HollowMicroblock$$super$occlusionTest(TMultiPart other) {
return super.occlusionTest(other);
}
public boolean codechicken$microblock$TMicroOcclusion$$super$occlusionTest(TMultiPart other) {
return super.occlusionTest(other);
}
public void codechicken$microblock$TMicroOcclusionClient$$super$onAdded() {
super.onAdded();
}
public void codechicken$microblock$TMicroOcclusionClient$$super$onPartChanged(TMultiPart other) {
super.onPartChanged(other);
}
public void codechicken$microblock$TMicroOcclusionClient$$super$read(MCDataInput packet) {
super.read(packet);
}
}
}
@@ -0,0 +1,248 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.*;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import net.minecraft.nbt.NBTTagCompound;
import org.junit.jupiter.api.Test;
import codechicken.lib.data.MCDataInput;
import codechicken.lib.data.MCDataOutputWrapper;
import codechicken.lib.raytracer.IndexedCuboid6;
import codechicken.lib.vec.Cuboid6;
import codechicken.microblock.FaceMicroClass;
import codechicken.microblock.HollowMicroClass$;
import codechicken.microblock.HollowMicroblock;
import codechicken.microblock.ISidedHollowConnect;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.Microblock;
import codechicken.microblock.MicroblockGenerator;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TileMultipart;
import scala.MatchError;
import scala.collection.JavaConversions;
import scala.collection.Seq;
class HollowMicroblockTraitsFunctionalTest {
@Test
void generatedHollowsKeepAllThicknessesOrientationsAndLiveConnectorOpenings() {
Microblock part = create();
HollowMicroblock hollow = (HollowMicroblock) part;
Connector connector = new Connector();
part.bind(new TileMultipart() {
@Override
public TMultiPart partMap(int slot) {
assertEquals(6, slot);
return connector;
}
});
assertSame(HollowMicroClass$.MODULE$, part.microClass());
assertEquals("mcr_hllw", part.getType());
for (int thickness = 1; thickness <= 7; thickness++) {
for (int side = 0; side < 6; side++) {
part.setShape(thickness, side);
for (int opening : new int[] { 0, 1, 8, 11 }) {
connector.size = opening;
assertEquals(opening, hollow.getHollowSize());
assertEquals(side, connector.lastSide);
double t = thickness / 8D;
double gap = opening / 16D;
assertEquals(t * (1 - gap * gap), volume(hollow.getCollisionBoxes()), 1e-12);
assertEquals(t * (0.75 * 0.75 - gap * gap), volume(hollow.getOcclusionBoxes()), 1e-12);
assertEquals(t * (1 - 0.75 * 0.75), volume(hollow.getPartialOcclusionBoxes()), 1e-12);
int axis = new int[] { 1, 2, 0 }[side / 2];
List<Cuboid6> collision = hollow.getCollisionBoxes();
List<IndexedCuboid6> subparts = hollow.getSubParts();
assertEquals(4, collision.size());
assertEquals(4, subparts.size());
for (int i = 0; i < 4; i++) {
Cuboid6 box = collision.get(i);
double[] min = { box.min.x, box.min.y, box.min.z };
double[] max = { box.max.x, box.max.y, box.max.z };
assertEquals((side & 1) == 0 ? 0 : 1 - t, min[axis], 1e-12);
assertEquals((side & 1) == 0 ? t : 1, max[axis], 1e-12);
assertBox(box, subparts.get(i));
assertEquals(0, subparts.get(i).data);
if (opening > 0) {
boolean missesCenter = false;
for (int j = 0; j < 3; j++) if (j != axis) missesCenter |= max[j] < 0.5 || min[j] > 0.5;
assertTrue(missesCenter, "central connector must fit through the hollow cover");
}
}
assertSame(FaceMicroClass.aBounds()[thickness * 16 + side], part.getBounds());
}
}
}
}
@Test
@SuppressWarnings("unchecked")
void partialBoxesRemainLiveJavaViewsAndBoundsKeepSignedIndexFailures() {
Microblock part = create();
HollowMicroblock hollow = (HollowMicroblock) part;
HollowMicroClass$ factory = HollowMicroClass$.MODULE$;
Cuboid6[] bounds = FaceMicroClass.aBounds();
Seq<Cuboid6>[] partial = factory.pBoxes();
Cuboid6 sentinel = new Cuboid6(0.1, 0.2, 0.3, 0.4, 0.5, 0.6);
part.setShape(3, 0);
try {
Cuboid6[] replacementBounds = new Cuboid6[256];
replacementBounds[48] = sentinel;
FaceMicroClass.aBounds_$eq(replacementBounds);
assertSame(sentinel, part.getBounds());
Seq<Cuboid6>[] replacement = (Seq<Cuboid6>[]) new Seq<?>[256];
List<Cuboid6> backing = new ArrayList<>(Arrays.asList(sentinel));
replacement[48] = JavaConversions.asScalaBuffer(backing);
factory.pBoxes_$eq(replacement);
List<Cuboid6> view = hollow.getPartialOcclusionBoxes();
assertSame(sentinel, view.get(0));
backing.add(Cuboid6.full);
assertEquals(2, view.size());
view.remove(0);
assertSame(Cuboid6.full, backing.get(0));
replacement[48] = null;
List<Cuboid6> nullView = hollow.getPartialOcclusionBoxes();
assertNotNull(nullView);
assertThrows(NullPointerException.class, nullView::size);
part.shape_$eq((byte) 0);
assertNull(part.getBounds());
for (int shape = -128; shape < 0; shape++) {
part.shape_$eq((byte) shape);
assertThrows(ArrayIndexOutOfBoundsException.class, part::getBounds);
assertThrows(ArrayIndexOutOfBoundsException.class, hollow::getPartialOcclusionBoxes);
}
part.setShape(3, 0);
factory.pBoxes_$eq((Seq<Cuboid6>[]) new Seq<?>[1]);
assertThrows(ArrayIndexOutOfBoundsException.class, hollow::getPartialOcclusionBoxes);
factory.pBoxes_$eq(null);
FaceMicroClass.aBounds_$eq(null);
assertThrows(NullPointerException.class, hollow::getPartialOcclusionBoxes);
assertThrows(NullPointerException.class, part::getBounds);
} finally {
factory.pBoxes_$eq(partial);
FaceMicroClass.aBounds_$eq(bounds);
}
}
@Test
void normalBoxesUseLiveBoundsAndKeepNullIndexAndInvalidSlotFailureOrder() {
Microblock part = create();
HollowMicroblock hollow = (HollowMicroblock) part;
HollowMicroClass$ factory = HollowMicroClass$.MODULE$;
Cuboid6[] original = factory.occBounds();
Cuboid6[] replacement = new Cuboid6[256];
replacement[48] = new Cuboid6(0.1, 0.2, 0.3, 0.9, 0.8, 0.7);
try {
factory.occBounds_$eq(replacement);
part.setShape(3, 0);
List<Cuboid6> boxes = (List<Cuboid6>) hollow.getOcclusionBoxes();
assertEquals(4, boxes.size());
assertBox(new Cuboid6(0.75, 0.2, 0.25, 0.9, 0.8, 0.75), boxes.get(0));
assertThrows(UnsupportedOperationException.class, () -> boxes.set(0, Cuboid6.full));
replacement[48].max.x = 0.8;
assertEquals(0.8, hollow.getOcclusionBoxes().iterator().next().max.x);
assertEquals(0.9, boxes.get(0).max.x);
for (int slot = 6; slot < 16; slot++) {
part.setShape(3, slot);
assertThrows(NullPointerException.class, hollow::getOcclusionBoxes);
replacement[48 + slot] = Cuboid6.full;
assertEquals(
Integer.toString(slot) + " (of class java.lang.Integer)",
assertThrows(MatchError.class, hollow::getOcclusionBoxes).getMessage());
}
part.shape_$eq((byte) -1);
assertThrows(ArrayIndexOutOfBoundsException.class, hollow::getOcclusionBoxes);
factory.occBounds_$eq(null);
assertThrows(NullPointerException.class, hollow::getOcclusionBoxes);
} finally {
factory.occBounds_$eq(original);
}
}
@Test
void allFortyTwoShapesKeepMaterialAndPackedNbtAndDescriptionBytes() {
Microblock part = create();
Microblock loaded = create();
ByteArrayOutputStream prefixBytes = new ByteArrayOutputStream();
MicroMaterialRegistry.writeMaterialID(new MCDataOutputWrapper(new DataOutputStream(prefixBytes)), 0);
byte[] prefix = prefixBytes.toByteArray();
for (int thickness = 1; thickness <= 7; thickness++) {
for (int side = 0; side < 6; side++) {
byte shape = (byte) (thickness * 16 + side);
part.setShape(thickness, side);
NBTTagCompound tag = new NBTTagCompound();
part.save(tag);
assertEquals(shape, tag.getByte("shape"));
assertEquals(MicroMaterialRegistry.materialName(0), tag.getString("material"));
loaded.load(tag);
assertEquals(shape, loaded.shape());
assertEquals(0, loaded.material());
assertSame(part.getBounds(), loaded.getBounds());
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
part.writeDesc(new MCDataOutputWrapper(new DataOutputStream(bytes)));
byte[] expected = Arrays.copyOf(prefix, prefix.length + 1);
expected[prefix.length] = shape;
assertArrayEquals(expected, bytes.toByteArray());
AtomicInteger reads = new AtomicInteger();
MCDataInput input = (MCDataInput) Proxy.newProxyInstance(
getClass().getClassLoader(),
new Class<?>[] { MCDataInput.class },
(proxy, method, args) -> {
assertEquals("readByte", method.getName());
reads.incrementAndGet();
return shape;
});
loaded.setShape(1, 0);
loaded.readDesc(input);
assertEquals(1, reads.get());
assertEquals(shape, loaded.shape());
assertSame(part.getBounds(), loaded.getBounds());
}
}
}
private static Microblock create() {
return MicroblockGenerator.create(HollowMicroClass$.MODULE$, 0, false);
}
private static double volume(Iterable<Cuboid6> boxes) {
double result = 0;
for (Cuboid6 box : boxes) result += (box.max.x - box.min.x) * (box.max.y - box.min.y) * (box.max.z - box.min.z);
return result;
}
private static void assertBox(Cuboid6 expected, Cuboid6 actual) {
assertArrayEquals(
new double[] { expected.min.x, expected.min.y, expected.min.z, expected.max.x, expected.max.y,
expected.max.z },
new double[] { actual.min.x, actual.min.y, actual.min.z, actual.max.x, actual.max.y, actual.max.z },
1e-12);
}
private static final class Connector extends TMultiPart implements ISidedHollowConnect {
int size;
int lastSide;
@Override
public String getType() {
return "test:hollow_connector";
}
@Override
public int getHollowSize(int side) {
lastSide = side;
return size;
}
}
}
@@ -0,0 +1,228 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.nbt.NBTTagCompound;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import codechicken.lib.asm.ASMHelper;
import codechicken.lib.vec.Cuboid6;
import codechicken.lib.vec.Rotation;
import codechicken.lib.vec.Vector3;
import codechicken.microblock.BlockMicroMaterial;
import codechicken.microblock.CornerMicroClass$;
import codechicken.microblock.EdgeMicroClass$;
import codechicken.microblock.FaceMicroClass$;
import codechicken.microblock.HollowMicroClass$;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.Microblock;
import codechicken.microblock.MicroblockClass;
import codechicken.microblock.MicroblockGenerator;
import codechicken.microblock.PostMicroClass$;
import codechicken.multipart.TileMultipart;
import codechicken.multipart.examples.IlluminatedMicroMaterial;
import codechicken.multipart.examples.IlluminatedMicroblockExample;
import codechicken.multipart.examples.IlluminatedMicroblockTrait;
class IlluminatedMicroblockFunctionalTest {
@Test
void registeredJavaMaterialComposesWithEveryShapeAndKeepsPersistenceAndClassCaching() throws Exception {
assertTrue(IlluminatedMicroblockTrait.class.isInterface());
assertThrows(
NoSuchMethodException.class,
() -> IlluminatedMicroblockTrait.class
.getDeclaredMethod("renderDynamic", Vector3.class, float.class, int.class));
for (int meta = 16; meta < 32; meta++) {
IlluminatedMicroMaterial material = (IlluminatedMicroMaterial) MicroMaterialRegistry
.getMaterial(BlockMicroMaterial.materialKey(ForgeMultipartFunctionalTestMod.illuminatedLamp, meta));
assertSame(ForgeMultipartFunctionalTestMod.illuminatedLamp, material.block());
assertEquals(meta, material.meta());
BitSet server = new BitSet();
server.set(10000);
BitSet client = (BitSet) server.clone();
material.addTraits(server, FaceMicroClass$.MODULE$, false);
material.addTraits(client, FaceMicroClass$.MODULE$, true);
assertEquals(server, client);
assertEquals(2, server.cardinality());
}
for (MicroblockClass factory : families()) {
Microblock first = create(factory, 19);
Microblock second = create(factory, 31);
assertTrue(first instanceof IlluminatedMicroblockTrait);
assertSame(factory, first.microClass());
assertSame(first.getClass(), second.getClass());
assertNotSame(first, second);
assertTrue(first.shouldRenderDynamic());
assertNull(first.tile());
first.setShape(3, slot(factory));
NBTTagCompound tag = new NBTTagCompound();
first.save(tag);
assertEquals(
BlockMicroMaterial.materialKey(ForgeMultipartFunctionalTestMod.illuminatedLamp, 19),
tag.getString("material"));
second.load(tag);
assertEquals(first.shape(), second.shape());
assertEquals(first.material(), second.material());
}
List<Integer> seenMetadata = new ArrayList<>();
Block lamp = new Block(Material.glass) {
@Override
public int getHarvestLevel(int metadata) {
seenMetadata.add(metadata);
return metadata;
}
};
for (int meta = 16; meta < 32; meta++) {
assertEquals(meta - 16, new IlluminatedMicroMaterial(lamp, meta, 0).getCutterStrength());
}
assertEquals(16, seenMetadata.size());
}
@Test
void lightAggregationUsesOnlyTraitMembersWithReferenceRoundingAndNoDetachedFilter() {
Microblock first = create(FaceMicroClass$.MODULE$, 16);
Microblock second = create(CornerMicroClass$.MODULE$, 17);
Microblock plain = FaceMicroClass$.MODULE$.create(false, MicroMaterialRegistry.materialID("minecraft:stone"));
TileMultipart tile = new TileMultipart();
first.bind(tile);
first.setShape(1, 0);
second.setShape(2, 7);
tile.setPartList(Arrays.asList(first, plain, second));
try {
IlluminatedMicroblockExample.dimLampParts = () -> true;
assertEquals(5, first.getLightValue());
assertNull(second.tile(), "Detached siblings are deliberately included by jPartList traversal");
second.setShape(7, 7);
assertEquals(15, first.getLightValue());
tile.setPartList(Arrays.asList(plain));
assertEquals(0, first.getLightValue());
IlluminatedMicroblockExample.dimLampParts = () -> false;
assertEquals(0, first.getLightValue());
tile.setPartList(Arrays.asList(second));
assertEquals(15, first.getLightValue());
first.bind(null);
assertThrows(NullPointerException.class, first::getLightValue);
} finally {
IlluminatedMicroblockExample.dimLampParts = () -> false;
}
}
@Test
void haloGeometryCopiesCollisionBoundsAndKeepsHollowOpeningOnEverySide() {
for (MicroblockClass factory : new MicroblockClass[] { FaceMicroClass$.MODULE$, CornerMicroClass$.MODULE$,
EdgeMicroClass$.MODULE$, PostMicroClass$.MODULE$ }) {
Microblock part = create(factory, 16);
part.setShape(2, slot(factory));
List<Cuboid6> original = new ArrayList<>();
for (Cuboid6 box : part.getCollisionBoxes()) original.add(box.copy());
List<Cuboid6> halo = IlluminatedMicroblockExample.haloBoxes(part);
assertEquals(original.size(), halo.size());
int i = 0;
for (Cuboid6 box : part.getCollisionBoxes()) {
assertBox(original.get(i), box);
assertBox(original.get(i).copy().expand(0.025), halo.get(i));
i++;
}
}
Microblock hollow = create(HollowMicroClass$.MODULE$, 18);
for (int side = 0; side < 6; side++) {
hollow.setShape(2, side);
List<Cuboid6> halo = IlluminatedMicroblockExample.haloBoxes(hollow);
assertEquals(4, halo.size());
// Default opening width is 8/16. These golden local bounds include the reference's trimmed middle strips.
Cuboid6[] local = { new Cuboid6(-0.025, -0.025, -0.025, 1.025, 0.275, 0.275),
new Cuboid6(-0.025, -0.025, 0.725, 1.025, 0.275, 1.025),
new Cuboid6(-0.025, -0.025, 0.275, 0.275, 0.275, 0.725),
new Cuboid6(0.725, -0.025, 0.275, 1.025, 0.275, 0.725) };
for (int i = 0; i < 4; i++) {
assertBox(local[i].apply(Rotation.sideRotations[side].at(Vector3.center)), halo.get(i));
}
}
}
@Test
void retainedClientMethodCompilesAndSubmitsHaloWithoutAClientOrGpu() throws Exception {
// Exercise the actual compiled client body with a uniquely named compiler probe. This does not simulate a
// physical
// client.
try {
ClassNode input = ASMHelper.createClassNode(
Launch.classLoader.getClassBytes("codechicken.multipart.examples.IlluminatedMicroblockTrait"),
0);
input.name = "codechicken/multipart/test/IlluminatedClientProbe";
MethodNode render = input.methods.stream().map(m -> (MethodNode) m)
.filter(m -> m.name.equals("renderDynamic")).findFirst().get();
assertTrue(render.visibleAnnotations.stream().anyMatch(a -> a.desc.endsWith("/SideOnly;")));
render.visibleAnnotations.clear(); // Keep just this body for the headless compiler probe.
MixinClassesFunctionalTest.COMPILER.registerJavaTrait(input);
Class<?> composite = MixinClassesFunctionalTest.COMPILER.mixinClasses(
"codechicken/multipart/test/IlluminatedClientComposite",
"codechicken/microblock/Microblock",
MixinClassesFunctionalTest.seq("codechicken/microblock/FaceMicroblock", input.name));
Microblock part = (Microblock) composite.getConstructor(int.class).newInstance(
MicroMaterialRegistry.materialID(
BlockMicroMaterial.materialKey(ForgeMultipartFunctionalTestMod.illuminatedLamp, 21)));
part.setShape(2, 0);
TileMultipart tile = new TileMultipart();
tile.xCoord = 4;
tile.yCoord = 5;
tile.zCoord = 6;
part.bind(tile);
List<Cuboid6> submitted = new ArrayList<>();
IlluminatedMicroblockExample.haloRenderer = (x, y, z, colour, bounds) -> {
assertEquals(Arrays.asList(4, 5, 6, 5), Arrays.asList(x, y, z, colour));
submitted.add(bounds);
};
java.lang.reflect.Method method = composite
.getDeclaredMethod("renderDynamic", Vector3.class, float.class, int.class);
method.invoke(part, new Vector3(99, 99, 99), 0.5F, 1);
assertTrue(submitted.isEmpty());
method.invoke(part, new Vector3(99, 99, 99), 0.5F, 0);
assertEquals(1, submitted.size());
assertBox(IlluminatedMicroblockExample.haloBoxes(part).get(0), submitted.get(0));
} finally {
IlluminatedMicroblockExample.haloRenderer = null;
}
}
private static int slot(MicroblockClass factory) {
if (factory == CornerMicroClass$.MODULE$) return 7;
if (factory == EdgeMicroClass$.MODULE$) return 15;
return 0;
}
private static MicroblockClass[] families() {
return new MicroblockClass[] { FaceMicroClass$.MODULE$, HollowMicroClass$.MODULE$, CornerMicroClass$.MODULE$,
EdgeMicroClass$.MODULE$, PostMicroClass$.MODULE$ };
}
private static Microblock create(MicroblockClass factory, int meta) {
return MicroblockGenerator.create(
factory,
MicroMaterialRegistry.materialID(
BlockMicroMaterial.materialKey(ForgeMultipartFunctionalTestMod.illuminatedLamp, meta)),
false);
}
private static void assertBox(Cuboid6 expected, Cuboid6 actual) {
assertEquals(expected.min.x, actual.min.x, 1e-9);
assertEquals(expected.min.y, actual.min.y, 1e-9);
assertEquals(expected.min.z, actual.min.z, 1e-9);
assertEquals(expected.max.x, actual.max.x, 1e-9);
assertEquals(expected.max.y, actual.max.y, 1e-9);
assertEquals(expected.max.z, actual.max.z, 1e-9);
}
}
@@ -0,0 +1,436 @@
package codechicken.multipart.test;
import static codechicken.multipart.test.MixinClassesFunctionalTest.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.objectweb.asm.Opcodes.*;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TypeInsnNode;
import codechicken.lib.asm.ASMHelper;
import codechicken.multipart.asm.ASMMixinCompiler.MixinInfo;
import cpw.mods.fml.common.asm.transformers.SideTransformer;
import scala.MatchError;
import scala.collection.JavaConversions;
class JavaTraitRegistrationFunctionalTest {
private static final String ROOT = "codechicken/multipart/test/javatrait/";
@Test
void rejectsInterfacesThenInnerClassesWithoutPublishing() throws Exception {
try (Scope scope = new Scope()) {
ClassNode input = input("Rejected", "java/lang/Object");
input.access |= ACC_INTERFACE | ACC_ABSTRACT;
input.visitInnerClass(input.name + "$Nested", input.name, "Nested", ACC_PUBLIC);
assertFailure(
input,
"Cannot register java interface " + input.name
+ " as a mixin trait. Try register passThroughInterface");
input.access &= ~ACC_INTERFACE;
assertFailure(
input,
"Inner classes are not permitted for " + input.name + " as a java mixin trait. Use scala");
assertFalse(scope.bytes.contains(input.name));
assertFalse(scope.bytes.contains(input.name + "$class"));
assertFalse(scope.mixins.contains(input.name));
}
}
@Test
void executesInitializationFieldAccessVirtualSelfCallsAndSuperDispatchWithoutMutatingInput() throws Exception {
try (Scope scope = new Scope()) {
ClassNode parent = base("JavaBase");
scope.define(parent);
ClassNode input = input("Executable", parent.name);
input.sourceFile = "OriginalJavaTrait.java";
input.visitField(ACC_PRIVATE, "count", "I", null, null);
MethodNode constructor = method(input, "<init>");
constructor.instructions.remove(constructor.instructions.getLast());
constructor.visitVarInsn(ALOAD, 0);
constructor.visitIntInsn(BIPUSH, 12);
constructor.visitFieldInsn(PUTFIELD, input.name, "count", "I");
constructor.visitInsn(RETURN);
constructor.visitMaxs(2, 1);
MethodVisitor increment = input
.visitMethod(ACC_PROTECTED, "increment", "(I)I", null, new String[] { "java/io/IOException" });
increment.visitVarInsn(ALOAD, 0);
increment.visitInsn(DUP);
increment.visitFieldInsn(GETFIELD, input.name, "count", "I");
increment.visitVarInsn(ILOAD, 1);
increment.visitInsn(IADD);
increment.visitFieldInsn(PUTFIELD, input.name, "count", "I");
increment.visitVarInsn(ALOAD, 0);
increment.visitFieldInsn(GETFIELD, input.name, "count", "I");
increment.visitInsn(IRETURN);
increment.visitMaxs(3, 2);
MethodVisitor call = input.visitMethod(ACC_PUBLIC, "call", "()I", null, null);
call.visitVarInsn(ALOAD, 0);
call.visitInsn(ICONST_3);
call.visitMethodInsn(INVOKEVIRTUAL, input.name, "increment", "(I)I", false);
call.visitInsn(IRETURN);
call.visitMaxs(2, 1);
MethodVisitor score = input.visitMethod(ACC_PUBLIC, "score", "()I", null, null);
score.visitVarInsn(ALOAD, 0);
score.visitMethodInsn(INVOKESPECIAL, parent.name, "score", "()I", false);
score.visitInsn(ICONST_2);
score.visitInsn(IADD);
score.visitInsn(IRETURN);
score.visitMaxs(2, 1);
byte[] before = ASMHelper.createBytes(input, 0);
COMPILER.internalDefine(input.name, before);
COMPILER.registerJavaTrait(input);
assertArrayEquals(before, ASMHelper.createBytes(input, 0));
MixinInfo info = COMPILER.getMixinInfo(input.name).get();
assertEquals(parent.name, info.parent());
assertEquals(Arrays.asList("score()I"), JavaConversions.seqAsJavaList(info.supers()));
assertEquals(Arrays.asList("increment(I)I", "call()I", "score()I"), signatures(info));
assertEquals("OriginalJavaTrait.java", COMPILER.classNode(input.name + "$class").sourceFile);
Object result = COMPILER.mixinClasses(ROOT + "ExecutableComposite", parent.name, seq(input.name))
.getConstructor(int.class).newInstance(20);
assertEquals(15, result.getClass().getMethod("call").invoke(result));
assertEquals(18, result.getClass().getMethod("call").invoke(result));
assertEquals(22, result.getClass().getMethod("score").invoke(result));
assertEquals(18, result.getClass().getMethod(input.name.replace('/', '$') + "$$count").invoke(result));
assertArrayEquals(
new Class<?>[] { java.io.IOException.class },
result.getClass().getMethod("increment", int.class).getExceptionTypes());
}
}
@Test
void matchingAccessorsAreSkippedBeforeConversionIncludingAnOtherwiseInvalidBody() throws Exception {
try (Scope scope = new Scope()) {
ClassNode parent = base("AccessorJavaBase");
scope.define(parent);
ClassNode input = input("Accessor", parent.name);
input.visitField(ACC_PUBLIC, "value", "I", null, null);
MethodVisitor getter = input.visitMethod(ACC_PUBLIC, "value", "()I", null, null);
getter.visitInsn(ICONST_1);
getter.visitIntInsn(NEWARRAY, T_INT);
getter.visitInsn(ARETURN);
getter.visitMaxs(1, 1);
constant(input, "value", "(I)I", 91, ACC_PUBLIC);
constant(input, "hidden", "()I", 6, ACC_PRIVATE);
COMPILER.registerJavaTrait(input);
MixinInfo info = COMPILER.getMixinInfo(input.name).get();
assertEquals(Arrays.asList("value(I)I"), signatures(info));
ClassNode helper = COMPILER.classNode(input.name + "$class");
assertEquals(ACC_PRIVATE | ACC_STATIC, method(helper, "hidden").access);
assertEquals(1, helper.methods.stream().filter(m -> ((MethodNode) m).name.equals("value")).count());
Object result = COMPILER.mixinClasses(ROOT + "AccessorComposite", parent.name, seq(input.name))
.getConstructor(int.class).newInstance(0);
result.getClass().getMethod("value_$eq", int.class).invoke(result, 28);
assertEquals(28, result.getClass().getMethod("value").invoke(result));
assertEquals(91, result.getClass().getMethod("value", int.class).invoke(result, 8));
}
}
@Test
void parentTraitsRetainTheirBaseAndDeduplicateTheImplementedInterface() throws Exception {
try (Scope scope = new Scope()) {
ClassNode parent = base("ParentJavaBase");
scope.define(parent);
ClassNode first = input("Parent", parent.name);
constant(first, "fromParent", "()I", 17, ACC_PUBLIC);
COMPILER.registerJavaTrait(first);
MixinInfo firstInfo = COMPILER.getMixinInfo(first.name).get();
ClassNode second = input("Child", first.name);
second.interfaces.add(first.name);
constant(second, "fromChild", "()I", 23, ACC_PUBLIC);
COMPILER.registerJavaTrait(second);
MixinInfo childInfo = COMPILER.getMixinInfo(second.name).get();
assertEquals(parent.name, childInfo.parent());
assertEquals(1, childInfo.parentTraits().size());
assertSame(firstInfo, childInfo.parentTraits().apply(0));
assertEquals(Arrays.asList(first.name), COMPILER.classNode(second.name).interfaces);
Object value = COMPILER.mixinClasses(ROOT + "ChildComposite", parent.name, seq(second.name))
.getConstructor(int.class).newInstance(9);
assertEquals(17, value.getClass().getMethod("fromParent").invoke(value));
assertEquals(23, value.getClass().getMethod("fromChild").invoke(value));
assertEquals(9, value.getClass().getMethod("score").invoke(value));
}
}
@Test
void childTraitSuperCallDispatchesToRegisteredParentTrait() throws Exception {
try (Scope scope = new Scope()) {
ClassNode parent = base("SuperChildJavaBase");
scope.define(parent);
ClassNode first = input("SuperParent", parent.name);
constant(first, "score", "()I", 17, ACC_PUBLIC);
COMPILER.registerJavaTrait(first);
ClassNode second = input("SuperChild", first.name);
MethodVisitor score = second.visitMethod(ACC_PUBLIC, "score", "()I", null, null);
score.visitVarInsn(ALOAD, 0);
score.visitMethodInsn(INVOKESPECIAL, first.name, "score", "()I", false);
score.visitInsn(ICONST_1);
score.visitInsn(IADD);
score.visitInsn(IRETURN);
score.visitMaxs(2, 1);
COMPILER.internalDefine(second.name, ASMHelper.createBytes(second, 0));
COMPILER.registerJavaTrait(second);
Object value = COMPILER.mixinClasses(ROOT + "SuperChildComposite", parent.name, seq(second.name))
.getConstructor(int.class).newInstance(9);
assertEquals(18, value.getClass().getMethod("score").invoke(value));
}
}
@Test
void childTraitSuperCallFallsBackToBaseWhenParentTraitDoesNotOverride() throws Exception {
try (Scope scope = new Scope()) {
ClassNode parent = base("SuperBaseChildJavaBase");
scope.define(parent);
ClassNode first = input("SuperBaseParent", parent.name);
constant(first, "fromParent", "()I", 17, ACC_PUBLIC);
COMPILER.registerJavaTrait(first);
ClassNode second = input("SuperBaseChild", first.name);
MethodVisitor score = second.visitMethod(ACC_PUBLIC, "score", "()I", null, null);
score.visitVarInsn(ALOAD, 0);
score.visitMethodInsn(INVOKESPECIAL, first.name, "score", "()I", false);
score.visitInsn(ICONST_1);
score.visitInsn(IADD);
score.visitInsn(IRETURN);
score.visitMaxs(2, 1);
COMPILER.internalDefine(second.name, ASMHelper.createBytes(second, 0));
COMPILER.registerJavaTrait(second);
Object value = COMPILER.mixinClasses(ROOT + "SuperBaseChildComposite", parent.name, seq(second.name))
.getConstructor(int.class).newInstance(9);
assertEquals(10, value.getClass().getMethod("score").invoke(value));
}
}
@Test
void sideOnlyAnnotationsStripOppositeJavaMembersAndInitializationOnTheServer() throws Exception {
try (Scope scope = new Scope()) {
ClassNode parent = base("SideJavaBase");
scope.define(parent);
ClassNode input = input("SideOnly", parent.name);
input.visitField(ACC_PRIVATE, "clientVisibleField", "I", null, null)
.visitAnnotation("Lcpw/mods/fml/relauncher/SideOnly;", true)
.visitEnum("value", "Lcpw/mods/fml/relauncher/Side;", "CLIENT");
input.visitField(ACC_PRIVATE, "clientInvisibleField", "I", null, null)
.visitAnnotation("Lcpw/mods/fml/relauncher/SideOnly;", false)
.visitEnum("value", "Lcpw/mods/fml/relauncher/Side;", "CLIENT");
input.visitField(ACC_PRIVATE, "serverField", "I", null, null)
.visitAnnotation("Lcpw/mods/fml/relauncher/SideOnly;", true)
.visitEnum("value", "Lcpw/mods/fml/relauncher/Side;", "SERVER");
MethodNode constructor = method(input, "<init>");
constructor.visitAnnotation("Lcpw/mods/fml/relauncher/SideOnly;", true)
.visitEnum("value", "Lcpw/mods/fml/relauncher/Side;", "CLIENT");
constructor.instructions.remove(constructor.instructions.getLast());
initialize(constructor, input.name, "clientVisibleField", 11);
initialize(constructor, input.name, "clientInvisibleField", 13);
initialize(constructor, input.name, "serverField", 17);
constructor.visitInsn(RETURN);
constructor.visitMaxs(2, 1);
constant(input, "clientVisible", "()I", 37, ACC_PUBLIC);
method(input, "clientVisible").visitAnnotation("Lcpw/mods/fml/relauncher/SideOnly;", true)
.visitEnum("value", "Lcpw/mods/fml/relauncher/Side;", "CLIENT");
constant(input, "clientInvisible", "()I", 41, ACC_PUBLIC);
method(input, "clientInvisible").visitAnnotation("Lcpw/mods/fml/relauncher/SideOnly;", false)
.visitEnum("value", "Lcpw/mods/fml/relauncher/Side;", "CLIENT");
MethodVisitor clientInvalid = input.visitMethod(ACC_PUBLIC, "clientInvalid", "()[I", null, null);
clientInvalid.visitInsn(ICONST_1);
clientInvalid.visitIntInsn(NEWARRAY, T_INT);
clientInvalid.visitInsn(ARETURN);
clientInvalid.visitMaxs(1, 1);
clientInvalid.visitAnnotation("Lcpw/mods/fml/relauncher/SideOnly;", true)
.visitEnum("value", "Lcpw/mods/fml/relauncher/Side;", "CLIENT");
constant(input, "serverVisible", "()I", 43, ACC_PUBLIC);
method(input, "serverVisible").visitAnnotation("Lcpw/mods/fml/relauncher/SideOnly;", true)
.visitEnum("value", "Lcpw/mods/fml/relauncher/Side;", "SERVER");
COMPILER.registerJavaTrait(input);
MixinInfo info = COMPILER.getMixinInfo(input.name).get();
assertEquals(Arrays.asList("serverVisible()I"), signatures(info));
assertEquals(1, info.fields().size());
assertEquals("serverField", info.fields().apply(0).name());
Object value = COMPILER.mixinClasses(ROOT + "SideComposite", parent.name, seq(input.name))
.getConstructor(int.class).newInstance(0);
assertThrows(NoSuchMethodException.class, () -> value.getClass().getMethod("clientVisible"));
assertThrows(NoSuchMethodException.class, () -> value.getClass().getMethod("clientInvisible"));
assertThrows(NoSuchMethodException.class, () -> value.getClass().getMethod("clientInvalid"));
assertEquals(43, value.getClass().getMethod("serverVisible").invoke(value));
String fieldPrefix = input.name.replace('/', '$') + "$$";
assertThrows(
NoSuchMethodException.class,
() -> value.getClass().getMethod(fieldPrefix + "clientVisibleField"));
assertThrows(
NoSuchMethodException.class,
() -> value.getClass().getMethod(fieldPrefix + "clientInvisibleField"));
assertEquals(0, value.getClass().getMethod(fieldPrefix + "serverField").invoke(value));
}
}
@Test
void alreadyStrippedForgeConstructorStillSuppliesAnEmptyMixinInitializer() throws Exception {
try (Scope scope = new Scope()) {
ClassNode parent = base("PrestrippedSideJavaBase");
scope.define(parent);
ClassNode input = input("PrestrippedSide", parent.name);
input.visitField(ACC_PRIVATE, "state", "I", null, null);
MethodNode constructor = method(input, "<init>");
constructor.visitAnnotation("Lcpw/mods/fml/relauncher/SideOnly;", true)
.visitEnum("value", "Lcpw/mods/fml/relauncher/Side;", "CLIENT");
constructor.instructions.remove(constructor.instructions.getLast());
initialize(constructor, input.name, "state", 29);
constructor.visitInsn(RETURN);
constructor.visitMaxs(2, 1);
constant(input, "available", "()I", 47, ACC_PUBLIC);
ClassNode stripped = ASMHelper.createClassNode(
new SideTransformer().transform(input.name, input.name, ASMHelper.createBytes(input, 0)),
0);
assertTrue(stripped.methods.stream().noneMatch(m -> ((MethodNode) m).name.equals("<init>")));
COMPILER.registerJavaTrait(stripped);
Object value = COMPILER.mixinClasses(ROOT + "PrestrippedSideComposite", parent.name, seq(input.name))
.getConstructor(int.class).newInstance(7);
assertEquals(7, value.getClass().getMethod("score").invoke(value));
assertEquals(47, value.getClass().getMethod("available").invoke(value));
assertEquals(0, value.getClass().getMethod(input.name.replace('/', '$') + "$$state").invoke(value));
}
}
@Test
void constructorArgumentsStaticInitializersAndInvalidSuperSequencesFailBeforePublishing() throws Exception {
try (Scope scope = new Scope()) {
ClassNode args = input("Arguments", "java/lang/Object");
method(args, "<init>").desc = "(I)V";
assertFailure(args, "Constructor arguments are not permitted " + args.name + " as a mixin trait");
ClassNode statics = input("StaticInitializer", "java/lang/Object");
constant(statics, "earlier", "()I", 5, ACC_PUBLIC);
MethodVisitor clinit = statics.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
clinit.visitInsn(RETURN);
assertFailure(statics, "Static initialisers are not permitted " + statics.name + " as a mixin trait");
ClassNode invalid = input("InvalidConstructor", "java/lang/Object");
MethodNode constructor = method(invalid, "<init>");
constructor.instructions.remove(constructor.instructions.getFirst());
IllegalArgumentException failure = assertThrows(
IllegalArgumentException.class,
() -> COMPILER.registerJavaTrait(invalid));
assertTrue(failure.getMessage().startsWith("Invalid constructor insn sequence " + invalid.name + "\n"));
for (ClassNode node : Arrays.asList(args, statics, invalid)) {
assertFalse(scope.bytes.contains(node.name));
assertFalse(scope.bytes.contains(node.name + "$class"));
assertFalse(scope.mixins.contains(node.name));
}
}
}
@Test
void primitiveArrayAndForeignFieldFailuresRetainTheirOriginalTypesAndInput() throws Exception {
try (Scope scope = new Scope()) {
ClassNode arrays = input("PrimitiveArray", "java/lang/Object");
MethodVisitor array = arrays.visitMethod(ACC_PUBLIC, "array", "()[I", null, null);
array.visitInsn(ICONST_1);
array.visitIntInsn(NEWARRAY, T_INT);
array.visitInsn(ARETURN);
array.visitMaxs(1, 1);
byte[] before = ASMHelper.createBytes(arrays, 0);
assertEquals(
"188 (of class java.lang.Integer)",
assertThrows(MatchError.class, () -> COMPILER.registerJavaTrait(arrays)).getMessage());
assertArrayEquals(before, ASMHelper.createBytes(arrays, 0));
ClassNode foreign = input("ForeignField", "java/lang/Object");
MethodVisitor read = foreign.visitMethod(ACC_PUBLIC, "read", "(Ljava/awt/Point;)I", null, null);
read.visitVarInsn(ALOAD, 1);
read.visitFieldInsn(GETFIELD, "java/awt/Point", "x", "I");
read.visitInsn(IRETURN);
read.visitMaxs(1, 2);
assertEquals(
"key not found: x",
assertThrows(java.util.NoSuchElementException.class, () -> COMPILER.registerJavaTrait(foreign))
.getMessage());
assertFalse(scope.mixins.contains(arrays.name));
assertFalse(scope.mixins.contains(foreign.name));
}
}
@Test
void inheritedVirtualCallsKeepTheExistingDescriptorShapedCast() throws Exception {
try (Scope scope = new Scope()) {
ClassNode parent = base("InheritedJavaBase");
scope.define(parent);
ClassNode input = input("Inherited", parent.name);
MethodVisitor read = input.visitMethod(ACC_PUBLIC, "read", "()I", null, null);
read.visitVarInsn(ALOAD, 0);
read.visitMethodInsn(INVOKEVIRTUAL, input.name, "score", "()I", false);
read.visitInsn(IRETURN);
read.visitMaxs(1, 1);
COMPILER.internalDefine(input.name, ASMHelper.createBytes(input, 0));
InvocationTargetException failure = assertThrows(
InvocationTargetException.class,
() -> COMPILER.registerJavaTrait(input));
assertInstanceOf(ClassFormatError.class, failure.getCause());
ClassNode helper = COMPILER.classNode(input.name + "$class");
MethodNode output = method(helper, "read");
AbstractInsnNode cast = output.instructions.getFirst().getNext();
assertEquals("L" + parent.name + ";", ((TypeInsnNode) cast).desc);
assertEquals(parent.name, ((MethodInsnNode) cast.getNext()).owner);
assertFalse(scope.mixins.contains(input.name));
}
}
@Test
void definitionFailureKeepsHelperAndByteCachesButDoesNotPublishMixinMetadata() throws Exception {
try (Scope scope = new Scope()) {
ClassNode input = input("AlreadyLoaded", "java/lang/Object");
scope.define(input);
InvocationTargetException failure = assertThrows(
InvocationTargetException.class,
() -> COMPILER.registerJavaTrait(input));
assertInstanceOf(LinkageError.class, failure.getCause());
assertTrue(scope.bytes.contains(input.name + "$class"));
assertEquals(ACC_PUBLIC | ACC_INTERFACE | ACC_ABSTRACT, COMPILER.classNode(input.name).access);
assertFalse(scope.mixins.contains(input.name));
assertNotNull(scope.loader.findClass((input.name + "$class").replace('/', '.')));
}
}
private static ClassNode input(String suffix, String parent) {
ClassNode node = node(ROOT + suffix, parent, ACC_PUBLIC);
MethodVisitor constructor = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
constructor.visitVarInsn(ALOAD, 0);
constructor.visitMethodInsn(INVOKESPECIAL, parent, "<init>", "()V", false);
constructor.visitInsn(RETURN);
constructor.visitMaxs(1, 1);
return node;
}
private static void constant(ClassNode node, String name, String desc, int value, int access) {
MethodVisitor method = node.visitMethod(access, name, desc, null, null);
method.visitLdcInsn(value);
method.visitInsn(IRETURN);
method.visitMaxs(1, desc.equals("(I)I") ? 2 : 1);
}
private static void initialize(MethodVisitor constructor, String owner, String field, int value) {
constructor.visitVarInsn(ALOAD, 0);
constructor.visitLdcInsn(value);
constructor.visitFieldInsn(PUTFIELD, owner, field, "I");
}
private static MethodNode method(ClassNode node, String name) {
return (MethodNode) node.methods.stream().filter(m -> ((MethodNode) m).name.equals(name)).findFirst().get();
}
private static List<String> signatures(MixinInfo info) {
return JavaConversions.seqAsJavaList(info.methods()).stream().map(m -> m.name + m.desc)
.collect(Collectors.toList());
}
private static void assertFailure(ClassNode input, String message) {
assertEquals(
message,
assertThrows(IllegalArgumentException.class, () -> COMPILER.registerJavaTrait(input)).getMessage());
}
}
@@ -0,0 +1,229 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import org.junit.jupiter.api.Test;
import codechicken.microblock.BlockMicroMaterial;
import codechicken.microblock.ItemMicroPart;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.MicroRecipe;
import codechicken.microblock.Saw;
import codechicken.microblock.handler.MicroblockProxy;
import scala.Tuple3;
/**
* Recipe behavior needs Forge startup because the item and material registries are initialized by the mod lifecycle.
*/
class MicroRecipeFunctionalTest {
@Test
void cuttingStoneUsesTheRealMaterialInsteadOfTheMissingPlaceholder() {
int material = MicroMaterialRegistry.materialID("minecraft:stone");
InventoryCrafting crafting = grid();
crafting.setInventorySlotContents(0, new ItemStack(new TestSaw(100)));
crafting.setInventorySlotContents(3, new ItemStack(Blocks.stone));
assertEquals(material, MicroRecipe.findMaterial(crafting.getStackInSlot(3)));
assertMicro(MicroRecipe.getCraftingResult(crafting), 2, 0, 4, material);
crafting.setInventorySlotContents(3, MicroRecipe.getCraftingResult(crafting));
assertMicro(MicroRecipe.getCraftingResult(crafting), 2, 0, 2, material);
}
@Test
void cuttingDarkOakLogsAndLeavesRetainsTheirMetadata() {
for (Block block : new Block[] { Blocks.log2, Blocks.leaves2 }) {
String name = BlockMicroMaterial.materialKey(block, 1);
assertTrue(MicroMaterialRegistry.getMaterial(name) instanceof BlockMicroMaterial);
int material = MicroMaterialRegistry.materialID(name);
InventoryCrafting crafting = grid();
crafting.setInventorySlotContents(0, new ItemStack(new TestSaw(100)));
crafting.setInventorySlotContents(3, new ItemStack(block, 1, 1));
assertMicro(MicroRecipe.getCraftingResult(crafting), 2, 0, 4, material);
ItemStack restored = MicroRecipe.create(1, 0, 8, material);
assertSame(Item.getItemFromBlock(block), restored.getItem());
assertEquals(1, restored.getItemDamage());
}
}
@Test
void recipeMetadataMaterialLookupAndCreationRoundTrip() {
int material = glassMaterial();
ItemStack recipeOutput = MicroRecipe.getRecipeOutput();
assertEquals(9, MicroRecipe.getRecipeSize());
assertMicro(recipeOutput, 1, 0, 1, MicroMaterialRegistry.materialID("minecraft:stone"));
ItemStack source = MicroMaterialRegistry.getMaterial(material).getItem();
ItemStack fullBlock = MicroRecipe.create(3, 0, 8, material);
assertNotSame(source, fullBlock);
assertEquals(3, fullBlock.stackSize);
assertEquals(material, MicroRecipe.findMaterial(fullBlock));
assertEquals(0, MicroRecipe.microClass(fullBlock));
assertEquals(8, MicroRecipe.microSize(fullBlock));
ItemStack tagged = source.copy();
tagged.setTagCompound((NBTTagCompound) recipeOutput.getTagCompound().copy());
assertEquals(-1, MicroRecipe.findMaterial(tagged));
}
@Test
void hollowRecipeWinsOverTheSimultaneouslyValidGluingRecipe() {
int material = glassMaterial();
InventoryCrafting crafting = grid();
for (int slot = 0; slot < 9; slot++) {
if (slot != 4) {
crafting.setInventorySlotContents(slot, micro(0, 1, material));
}
}
assertMicro(MicroRecipe.getHollowResult(crafting), 8, 1, 1, material);
assertStack(MicroRecipe.getGluingResult(crafting), 1, 0, 8, material);
assertMicro(MicroRecipe.getCraftingResult(crafting), 8, 1, 1, material);
assertTrue(MicroRecipe.matches(crafting, null));
assertFalse(MicroRecipe.matches(grid(), null));
}
@Test
void gluingHandlesCoverHollowEdgeAndCornerForms() {
int material = glassMaterial();
assertMicro(MicroRecipe.getGluingResult(filled(2, 0, 1, material)), 1, 0, 2, material);
assertMicro(MicroRecipe.getGluingResult(filled(2, 1, 1, material)), 1, 1, 2, material);
assertMicro(MicroRecipe.getGluingResult(filled(2, 2, 1, material)), 1, 3, 1, material);
assertMicro(MicroRecipe.getGluingResult(filled(4, 2, 1, material)), 1, 0, 1, material);
assertMicro(MicroRecipe.getGluingResult(filled(2, 3, 1, material)), 1, 0, 1, material);
assertStack(MicroRecipe.getGluingResult(filled(2, 0, 4, material)), 1, 0, 8, material);
InventoryCrafting mixedEdges = grid();
mixedEdges.setInventorySlotContents(0, micro(2, 1, material));
mixedEdges.setInventorySlotContents(1, micro(2, 2, material));
assertNull(MicroRecipe.getGluingResult(mixedEdges));
assertNull(MicroRecipe.getGluingResult(filled(1, 0, 1, material)));
}
@Test
void thinningCutsRawMaterialsAndMicroblocksVertically() {
int material = glassMaterial();
TestSaw firstSaw = new TestSaw(100);
TestSaw laterSaw = new TestSaw(100);
InventoryCrafting raw = grid();
raw.setInventorySlotContents(0, new ItemStack(firstSaw));
raw.setInventorySlotContents(3, MicroMaterialRegistry.getMaterial(material).getItem());
raw.setInventorySlotContents(8, new ItemStack(laterSaw));
Tuple3<Saw, Object, Object> found = MicroRecipe.getSaw(raw);
assertSame(firstSaw, found._1());
assertEquals(0, ((Number) found._2()).intValue());
assertEquals(0, ((Number) found._3()).intValue());
raw.setInventorySlotContents(8, null);
assertStack(MicroRecipe.getThinningResult(raw), 2, 0, 4, material);
assertStack(MicroRecipe.getCraftingResult(raw), 2, 0, 4, material);
InventoryCrafting hollow = grid();
hollow.setInventorySlotContents(1, new ItemStack(firstSaw));
hollow.setInventorySlotContents(4, micro(1, 4, material));
assertMicro(MicroRecipe.getThinningResult(hollow), 2, 1, 2, material);
hollow.setInventorySlotContents(8, micro(0, 1, material));
assertNull(MicroRecipe.getThinningResult(hollow));
}
@Test
void splittingMapsEachSupportedClassHorizontally() {
int material = glassMaterial();
TestSaw saw = new TestSaw(100);
int[][] mappings = { { 0, 3 }, { 1, 3 }, { 3, 2 } };
for (int[] mapping : mappings) {
InventoryCrafting crafting = grid();
crafting.setInventorySlotContents(3, new ItemStack(saw));
crafting.setInventorySlotContents(4, micro(mapping[0], 2, material));
assertMicro(MicroRecipe.getSplittingResult(crafting), 2, mapping[1], 2, material);
assertMicro(MicroRecipe.getCraftingResult(crafting), 2, mapping[1], 2, material);
}
InventoryCrafting unsupported = grid();
unsupported.setInventorySlotContents(0, new ItemStack(saw));
unsupported.setInventorySlotContents(1, micro(2, 1, material));
assertNull(MicroRecipe.getSplittingResult(unsupported));
}
@Test
void hollowFillTurnsExactlyOneHollowPartBackIntoACover() {
int material = glassMaterial();
InventoryCrafting crafting = grid();
crafting.setInventorySlotContents(8, micro(1, 4, material));
assertMicro(MicroRecipe.getHollowFillResult(crafting), 1, 0, 4, material);
assertMicro(MicroRecipe.getCraftingResult(crafting), 1, 0, 4, material);
crafting.setInventorySlotContents(0, micro(1, 4, material));
assertNull(MicroRecipe.getHollowFillResult(crafting));
}
private static int glassMaterial() {
return MicroRecipe.findMaterial(new ItemStack(Blocks.glass));
}
private static ItemStack micro(int microClass, int size, int material) {
return ItemMicroPart.create(microClass << 8 | size, material);
}
private static InventoryCrafting filled(int count, int microClass, int size, int material) {
InventoryCrafting crafting = grid();
for (int slot = 0; slot < count; slot++) {
crafting.setInventorySlotContents(slot, micro(microClass, size, material));
}
return crafting;
}
private static InventoryCrafting grid() {
return new InventoryCrafting(new Container() {
@Override
public boolean canInteractWith(EntityPlayer player) {
return false;
}
}, 3, 3);
}
private static void assertMicro(ItemStack stack, int amount, int microClass, int size, int material) {
assertSame(MicroblockProxy.itemMicro(), stack.getItem());
assertStack(stack, amount, microClass, size, material);
}
private static void assertStack(ItemStack stack, int amount, int microClass, int size, int material) {
assertEquals(amount, stack.stackSize);
assertEquals(microClass, MicroRecipe.microClass(stack));
assertEquals(size, MicroRecipe.microSize(stack));
assertEquals(material, MicroRecipe.microMaterial(stack));
}
private static final class TestSaw extends Item implements Saw {
private final int strength;
private TestSaw(int strength) {
this.strength = strength;
}
@Override
public int getCuttingStrength(ItemStack item) {
return strength;
}
}
}
@@ -0,0 +1,31 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.reflect.Field;
import java.util.Map;
import net.minecraftforge.common.MinecraftForge;
import org.junit.jupiter.api.Test;
import codechicken.microblock.handler.MicroblockEventHandler;
import codechicken.microblock.handler.MicroblockEventHandler$;
import cpw.mods.fml.common.eventhandler.EventBus;
class MicroblockEventHandlerFunctionalTest {
@Test
void dedicatedServerRegistersTheCompanionAfterStrippingClientHandlers() throws Exception {
assertEquals(0, MicroblockEventHandler.class.getDeclaredMethods().length);
assertEquals(0, MicroblockEventHandler$.class.getDeclaredMethods().length);
assertTrue(listenerOwners(MinecraftForge.EVENT_BUS).containsKey(MicroblockEventHandler$.MODULE$));
}
private static Map<?, ?> listenerOwners(EventBus bus) throws Exception {
Field ownersField = EventBus.class.getDeclaredField("listenerOwners");
ownersField.setAccessible(true);
return (Map<?, ?>) ownersField.get(bus);
}
}
@@ -0,0 +1,250 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.reflect.Proxy;
import java.util.BitSet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import net.minecraft.nbt.NBTTagCompound;
import org.junit.jupiter.api.Test;
import codechicken.microblock.CornerMicroClass$;
import codechicken.microblock.EdgeMicroClass$;
import codechicken.microblock.FaceMicroClass$;
import codechicken.microblock.FaceMicroblock;
import codechicken.microblock.HollowMicroClass$;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.MicroMaterialRegistry.IMicroMaterial;
import codechicken.microblock.Microblock;
import codechicken.microblock.MicroblockClass;
import codechicken.microblock.MicroblockGenerator;
import codechicken.microblock.MicroblockGenerator$;
import codechicken.microblock.PostMicroClass$;
import codechicken.multipart.TileMultipart;
import codechicken.multipart.examples.MicroblockCreationExample;
import scala.Tuple2;
class MicroblockGeneratorFunctionalTest {
@Test
void externalMaterialTraitComposesWithEveryBuiltInShapeAndReusesClasses() throws Exception {
Tuple2<String, IMicroMaterial>[] materials = MicroMaterialRegistry.getIdMap();
Tuple2<String, IMicroMaterial> original = materials[0];
IMicroMaterial material = (IMicroMaterial) Proxy.newProxyInstance(
getClass().getClassLoader(),
new Class<?>[] { IMicroMaterial.class, MicroblockGenerator.IGeneratedMaterial.class },
(proxy, method, args) -> {
if ("addTraits".equals(method.getName())) {
((BitSet) args[0]).set(ForgeMultipartFunctionalTestMod.externalScalaMicroblockTraitId);
}
return defaultValue(method.getReturnType());
});
materials[0] = new Tuple2<>(original._1(), material);
try {
Class<?> trait = Class.forName("codechicken.multipart.test.ExternalScalaMicroblockFixture");
for (MicroblockClass factory : new MicroblockClass[] { FaceMicroClass$.MODULE$, HollowMicroClass$.MODULE$,
CornerMicroClass$.MODULE$, EdgeMicroClass$.MODULE$, PostMicroClass$.MODULE$ }) {
Microblock first = MicroblockGenerator.create(factory, 0, false);
Microblock second = MicroblockGenerator.create(factory, 0, false);
assertSame(factory, first.microClass());
assertSame(first.getClass(), second.getClass());
assertNotSame(first, second);
assertTrue(trait.isInstance(first));
assertTrue(first.shouldRenderDynamic());
assertEquals(41, first.getLightValue());
assertEquals(0, first.material());
assertNull(first.tile());
}
} finally {
materials[0] = original;
MicroblockGenerator.freshBitSet();
}
}
@Test
void javaExampleCapturesSourceShapeBeforeMaterialCallbacksRun() {
Microblock source = MicroblockGenerator.create(FaceMicroClass$.MODULE$, 0, false);
source.shape_$eq((byte) 0x25);
Tuple2<String, IMicroMaterial>[] materials = MicroMaterialRegistry.getIdMap();
Tuple2<String, IMicroMaterial> original = materials[0];
IMicroMaterial material = (IMicroMaterial) Proxy.newProxyInstance(
getClass().getClassLoader(),
new Class<?>[] { IMicroMaterial.class, MicroblockGenerator.IGeneratedMaterial.class },
(proxy, method, args) -> {
if ("addTraits".equals(method.getName())) source.shape_$eq((byte) 0x51);
return defaultValue(method.getReturnType());
});
materials[0] = new Tuple2<>(original._1(), material);
try {
Microblock created = MicroblockCreationExample.recreateForSide(source, false);
assertEquals(0x25, created.shape());
assertEquals(0x51, source.shape(), "Material callbacks can have side effects");
} finally {
materials[0] = original;
MicroblockGenerator.freshBitSet();
}
}
@Test
void javaExamplePreservesEveryShapeByteWithoutCopyingBindingsOrChangingTheSource() {
Microblock source = MicroblockGenerator.create(FaceMicroClass$.MODULE$, 0, false);
TileMultipart sourceTile = new TileMultipart();
source.bind(sourceTile);
for (int shape = Byte.MIN_VALUE; shape <= Byte.MAX_VALUE; shape++) {
source.shape_$eq((byte) shape);
Microblock created = MicroblockCreationExample.recreateForSide(source, false);
assertNotSame(source, created);
assertSame(source.getClass(), created.getClass());
assertSame(source.microClass(), created.microClass());
assertEquals(source.material(), created.material());
assertEquals((byte) shape, created.shape());
assertNull(created.tile());
assertSame(sourceTile, source.tile());
assertEquals((byte) shape, source.shape());
}
}
@Test
void staticAndCompanionReflectionCreateFreshPartsBeforeCallerOwnedShapeLoading() throws Exception {
MicroblockClass factory = FaceMicroClass$.MODULE$;
int material = MicroMaterialRegistry.materialID("minecraft:stone");
Microblock source = factory.create(false, material);
source.shape_$eq((byte) 0x25);
TileMultipart sourceTile = new TileMultipart();
source.bind(sourceTile);
for (Class<?> owner : new Class<?>[] { MicroblockGenerator.class, MicroblockGenerator$.class }) {
Object receiver = owner == MicroblockGenerator.class ? null : MicroblockGenerator$.MODULE$;
Microblock created = (Microblock) owner.getMethod("create", MicroblockClass.class, int.class, boolean.class)
.invoke(receiver, factory, material, false);
assertNotSame(source, created);
assertSame(source.getClass(), created.getClass());
assertSame(factory, created.microClass());
assertEquals(material, created.material());
assertEquals(0, created.shape());
assertNull(created.tile());
created.shape_$eq(source.shape());
assertEquals(0x25, created.shape());
NBTTagCompound tag = new NBTTagCompound();
tag.setString("material", "minecraft:stone");
tag.setByte("shape", (byte) 0x31);
created.load(tag);
assertEquals(0x31, created.shape());
assertEquals(material, created.material());
assertNull(created.tile());
assertSame(sourceTile, source.tile());
assertEquals(0x25, source.shape());
}
}
@Test
void materialCallbackFailurePropagatesAndTheNextCreationClearsScratch() {
Tuple2<String, IMicroMaterial>[] materials = MicroMaterialRegistry.getIdMap();
Tuple2<String, IMicroMaterial> original = materials[0];
IllegalStateException failure = new IllegalStateException("material trait failure");
BitSet scratch = MicroblockGenerator.getBitSet();
IMicroMaterial material = (IMicroMaterial) Proxy.newProxyInstance(
getClass().getClassLoader(),
new Class<?>[] { IMicroMaterial.class, MicroblockGenerator.IGeneratedMaterial.class },
(proxy, method, args) -> {
if ("addTraits".equals(method.getName())) {
assertSame(scratch, args[0]);
assertSame(FaceMicroClass$.MODULE$, args[1]);
assertEquals(Boolean.FALSE, args[2]);
((BitSet) args[0]).set(2048);
throw failure;
}
return defaultValue(method.getReturnType());
});
materials[0] = new Tuple2<>(original._1(), material);
try {
assertSame(
failure,
assertThrows(
IllegalStateException.class,
() -> MicroblockGenerator.create(FaceMicroClass$.MODULE$, 0, false)));
assertTrue(scratch.get(2048));
assertSame(
failure,
assertThrows(
IllegalStateException.class,
() -> MicroblockGenerator$.MODULE$.create(FaceMicroClass$.MODULE$, 0, false)));
materials[0] = original;
Microblock created = MicroblockGenerator.create(FaceMicroClass$.MODULE$, 0, false);
assertFalse(scratch.get(2048));
assertSame(FaceMicroClass$.MODULE$, created.microClass());
assertNull(created.tile());
} finally {
materials[0] = original;
MicroblockGenerator.freshBitSet();
}
}
@Test
void generatedMaterialAddsExternalScalaTraitBeforeConstruction() throws Exception {
Tuple2<String, IMicroMaterial>[] materials = MicroMaterialRegistry.getIdMap();
Tuple2<String, IMicroMaterial> original = materials[0];
AtomicInteger calls = new AtomicInteger();
AtomicReference<BitSet> callbackBits = new AtomicReference<>();
AtomicReference<BitSet> initialTraits = new AtomicReference<>();
IMicroMaterial material = (IMicroMaterial) Proxy.newProxyInstance(
getClass().getClassLoader(),
new Class<?>[] { IMicroMaterial.class, MicroblockGenerator.IGeneratedMaterial.class },
(proxy, method, args) -> {
if ("addTraits".equals(method.getName())) {
calls.incrementAndGet();
BitSet traits = (BitSet) args[0];
callbackBits.set(traits);
initialTraits.set((BitSet) traits.clone());
assertSame(FaceMicroClass$.MODULE$, args[1]);
assertEquals(Boolean.FALSE, args[2]);
traits.set(ForgeMultipartFunctionalTestMod.externalScalaMicroblockTraitId);
}
return defaultValue(method.getReturnType());
});
BitSet scratch = MicroblockGenerator.freshBitSet();
scratch.set(2048);
materials[0] = new Tuple2<>(original._1(), material);
try {
Microblock generated = MicroblockGenerator.create(FaceMicroClass$.MODULE$, 0, false);
BitSet expectedInitial = new BitSet();
expectedInitial.set(FaceMicroClass$.MODULE$.baseTraitId());
assertEquals(1, calls.get());
assertSame(scratch, callbackBits.get());
assertEquals(expectedInitial, initialTraits.get());
assertFalse(initialTraits.get().get(2048));
assertTrue(generated instanceof FaceMicroblock);
assertTrue(
Class.forName("codechicken.multipart.test.ExternalScalaMicroblockFixture").isInstance(generated));
assertEquals(0, generated.material());
assertTrue(generated.shouldRenderDynamic());
assertEquals(41, generated.getLightValue());
} finally {
materials[0] = original;
MicroblockGenerator.freshBitSet();
}
}
private static Object defaultValue(Class<?> type) {
if (type == boolean.class) return false;
if (type == byte.class) return (byte) 0;
if (type == short.class) return (short) 0;
if (type == int.class) return 0;
if (type == long.class) return 0L;
if (type == float.class) return 0F;
if (type == double.class) return 0D;
if (type == char.class) return (char) 0;
return null;
}
}
@@ -0,0 +1,37 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.handler.MicroblockMod;
import codechicken.microblock.handler.MicroblockMod$;
import codechicken.microblock.handler.MicroblockProxy;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
class MicroblockModFunctionalTest {
@Test
void fmlUsesTheCompanionAndCompletesTheMicroblockLifecycle() {
ModContainer container = Loader.instance().getIndexedModList().get("ForgeMicroblock");
assertNotNull(container);
assertSame(MicroblockMod$.MODULE$, container.getMod());
assertNotNull(MicroblockProxy.logger());
assertNotNull(MicroblockProxy.itemMicro());
assertNotNull(MicroblockProxy.sawStone());
assertNotNull(MicroblockProxy.sawIron());
assertNotNull(MicroblockProxy.sawDiamond());
assertNotNull(MicroblockProxy.stoneRod());
assertNotNull(MicroMaterialRegistry.getIdMap());
assertTrue(MicroMaterialRegistry.getIdMap().length > 0);
assertNotNull(MicroMaterialRegistry.getMaterial(MicroMaterialRegistry.getMissingId()));
assertTrue(MicroMaterialRegistry.getMaxCuttingStrength() >= 3);
assertNull(MicroblockMod.angelicaCompat());
}
}
@@ -0,0 +1,86 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.util.FakePlayerFactory;
import org.junit.jupiter.api.Test;
import codechicken.lib.packet.PacketCustom;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.handler.MicroblockSPH;
import cpw.mods.fml.common.network.internal.FMLProxyPacket;
import scala.Tuple2;
class MicroblockPacketHandlerFunctionalTest {
@Test
void javaEnumerationUsesTheSameIdsAsTheInitializedRegistryAndHandshake() {
PacketCustom outgoing = new PacketCustom("test", 1);
MicroMaterialRegistry.writeIDMap(outgoing);
PacketCustom incoming = new PacketCustom(outgoing.getByteBuf().copy());
int count = MicroMaterialRegistry.materialCount();
assertTrue(count > 0);
assertEquals(count, incoming.readInt());
for (int id = 0; id < count; id++) {
String name = MicroMaterialRegistry.materialName(id);
assertEquals(name, incoming.readString());
assertEquals(id, MicroMaterialRegistry.materialID(name));
assertNotNull(MicroMaterialRegistry.getMaterial(id));
assertSame(MicroMaterialRegistry.getMaterial(name), MicroMaterialRegistry.getMaterial(id));
}
assertEquals(0, incoming.getByteBuf().readableBytes());
}
@Test
void sendsTheCompleteMaterialIdMapDuringTheServerHandshake() {
MinecraftServer server = MinecraftServer.getServer();
WorldServer world = server.worldServers[0];
EntityPlayerMP player = FakePlayerFactory.getMinecraft(world);
NetHandlerPlayServer previousHandler = player.playerNetServerHandler;
RecordingNetHandler handler = new RecordingNetHandler(server, player);
try {
MicroblockSPH.handshakeRecieved(handler);
} finally {
player.playerNetServerHandler = previousHandler;
}
FMLProxyPacket sent = assertInstanceOf(FMLProxyPacket.class, handler.sent);
assertEquals("ForgeMicroblock", sent.channel());
PacketCustom payload = new PacketCustom(sent.payload().copy());
assertEquals(1, payload.getType());
Tuple2<String, MicroMaterialRegistry.IMicroMaterial>[] materials = MicroMaterialRegistry.getIdMap();
assertEquals(materials.length, payload.readInt());
for (Tuple2<String, MicroMaterialRegistry.IMicroMaterial> material : materials) {
assertEquals(material._1(), payload.readString());
}
assertEquals(0, payload.getByteBuf().readableBytes());
}
private static final class RecordingNetHandler extends NetHandlerPlayServer {
private Packet sent;
private RecordingNetHandler(MinecraftServer server, EntityPlayerMP player) {
super(server, new NetworkManager(false), player);
}
@Override
public void sendPacket(Packet packet) {
assertNotNull(packet);
sent = packet;
}
}
}
@@ -0,0 +1,299 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.util.FakePlayerFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import codechicken.lib.raytracer.ExtendedMOP;
import codechicken.lib.vec.BlockCoord;
import codechicken.microblock.AdditionPlacement;
import codechicken.microblock.CommonMicroblock;
import codechicken.microblock.EdgePlacement$;
import codechicken.microblock.EdgePlacementGrid$;
import codechicken.microblock.ExecutablePlacement;
import codechicken.microblock.ExpandingPlacement;
import codechicken.microblock.FaceMicroClass$;
import codechicken.microblock.FacePlacement$;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.Microblock;
import codechicken.microblock.MicroblockClass;
import codechicken.microblock.MicroblockPlacement;
import codechicken.microblock.MicroblockPlacement$;
import codechicken.microblock.PlacementGrid;
import codechicken.microblock.PlacementProperties;
import codechicken.microblock.PostMicroClass$;
import codechicken.microblock.PostMicroblock;
import codechicken.multipart.ControlKeyModifer;
import codechicken.multipart.TileMultipart;
import scala.Tuple2;
class MicroblockPlacementFunctionalTest {
private static final BlockCoord EXTERNAL_POS = new BlockCoord(160, 200, 160);
private static final BlockCoord INTERNAL_POS = new BlockCoord(164, 200, 160);
private static final BlockCoord EXPAND_POS = new BlockCoord(168, 200, 160);
private static final BlockCoord CUSTOM_POS = new BlockCoord(172, 200, 160);
private static final BlockCoord POST_POS = new BlockCoord(176, 200, 160);
private static final BlockCoord POST_EXPAND_POS = new BlockCoord(180, 200, 160);
private WorldServer world;
private EntityPlayer player;
private int material;
@BeforeEach
void setUp() {
world = MinecraftServer.getServer().worldServers[0];
assertNotNull(world);
player = FakePlayerFactory.getMinecraft(world);
assertNotNull(player);
player.setSneaking(false);
ControlKeyModifer.map().clear();
material = MicroMaterialRegistry.materialID("minecraft:stone");
assertTrue(material >= 0);
clearPositions();
}
@AfterEach
void tearDown() {
player.setSneaking(false);
ControlKeyModifer.map().clear();
clearPositions();
}
@Test
void selectsPlacesAndConsumesAnExternalFace() {
world.setBlock(EXTERNAL_POS.x, EXTERNAL_POS.y, EXTERNAL_POS.z, Blocks.stone);
MovingObjectPosition hit = hit(EXTERNAL_POS, 1.0);
MicroblockPlacement decision = new MicroblockPlacement(player, hit, 1, material, true, FacePlacement$.MODULE$);
ExecutablePlacement placement = decision.apply();
AdditionPlacement addition = assertInstanceOf(AdditionPlacement.class, placement);
BlockCoord target = EXTERNAL_POS.copy().offset(1);
assertEquals(target, addition.pos());
assertEquals(0, slot(addition.part()));
assertSame(player, decision.player());
assertSame(hit, decision.hit());
assertSame(world, decision.world());
assertSame(FaceMicroClass$.MODULE$, decision.mcrClass());
assertEquals(EXTERNAL_POS, decision.pos());
assertEquals(0, decision.slot());
assertEquals(1, decision.oslot());
assertEquals(1.0, decision.d());
assertFalse(decision.internal());
assertFalse(decision.oppMod());
ItemStack stack = new ItemStack(net.minecraft.init.Items.stick, 3);
addition.place(world, player, stack);
addition.consume(world, player, stack);
TileMultipart tile = TileMultipart.getTile(world, target);
assertNotNull(tile);
assertSame(addition.part(), tile.jPartList().get(0));
assertEquals(2, stack.stackSize);
}
@Test
void selectsTheInternalOrOppositeSlotFromTheControlModifier() {
player.setSneaking(true);
TileMultipart tile = TileMultipart.addPart(world, INTERNAL_POS, face(1, 2));
MicroblockPlacement normal = new MicroblockPlacement(
player,
hit(INTERNAL_POS, 0.25),
1,
material,
true,
FacePlacement$.MODULE$);
AdditionPlacement normalPlacement = assertInstanceOf(AdditionPlacement.class, normal.apply());
assertTrue(normal.internal());
assertFalse(normal.doExpand());
assertEquals(0, slot(normalPlacement.part()));
normalPlacement.place(world, player, new ItemStack(net.minecraft.init.Items.stick));
assertSame(normalPlacement.part(), tile.partMap(0));
clear(INTERNAL_POS);
tile = TileMultipart.addPart(world, INTERNAL_POS, face(1, 2));
ControlKeyModifer.map().put(player, true);
MicroblockPlacement opposite = new MicroblockPlacement(
player,
hit(INTERNAL_POS, 0.25),
1,
material,
true,
FacePlacement$.MODULE$);
AdditionPlacement oppositePlacement = assertInstanceOf(AdditionPlacement.class, opposite.apply());
assertTrue(opposite.oppMod());
assertEquals(1, slot(oppositePlacement.part()));
oppositePlacement.place(world, player, new ItemStack(net.minecraft.init.Items.stick));
assertSame(oppositePlacement.part(), tile.partMap(1));
}
@Test
void expandsTheHitPartInPlaceAndConsumesOneItem() {
Microblock original = face(1, 0);
TileMultipart tile = TileMultipart.addPart(world, EXPAND_POS, original);
ExtendedMOP hit = indexedHit(EXPAND_POS, 0.25, 0);
MicroblockPlacement decision = new MicroblockPlacement(player, hit, 1, material, true, FacePlacement$.MODULE$);
ExpandingPlacement placement = assertInstanceOf(ExpandingPlacement.class, decision.apply());
assertTrue(decision.internal());
assertTrue(decision.doExpand());
assertEquals(2, placement.part().getSize());
assertEquals(0, slot(placement.part()));
ItemStack stack = new ItemStack(net.minecraft.init.Items.stick, 3);
placement.place(world, player, stack);
placement.consume(world, player, stack);
assertSame(original, tile.jPartList().get(0));
assertEquals(2, original.getSize());
assertEquals(0, slot(original));
assertEquals(2, stack.stackSize);
}
@Test
void customPlacementWinsEvenWhenTheGridRejectsTheHit() {
world.setBlock(CUSTOM_POS.x, CUSTOM_POS.y, CUSTOM_POS.z, Blocks.stone);
ExecutablePlacement marker = new AdditionPlacement(CUSTOM_POS, null);
PlacementProperties properties = new PlacementProperties() {
@Override
public int opposite(int slot, int side) {
return slot;
}
@Override
public MicroblockClass microClass() {
return FaceMicroClass$.MODULE$;
}
@Override
public PlacementGrid placementGrid() {
return EdgePlacementGrid$.MODULE$;
}
@Override
public ExecutablePlacement customPlacement(MicroblockPlacement placement) {
return marker;
}
};
ExecutablePlacement result = MicroblockPlacement$.MODULE$
.apply(player, hit(CUSTOM_POS, 1.0), 2, material, false, properties);
assertSame(marker, result);
}
@Test
void edgeCustomPlacementCreatesOnlyEvenPostsAtTheGridCentre() {
world.setBlock(POST_POS.x, POST_POS.y, POST_POS.z, Blocks.stone);
MovingObjectPosition centreHit = hit(POST_POS, 1.0);
MicroblockPlacement odd = new MicroblockPlacement(player, centreHit, 1, material, true, EdgePlacement$.MODULE$);
assertEquals(-1, odd.slot());
assertNull(odd.apply());
MicroblockPlacement even = new MicroblockPlacement(
player,
centreHit,
2,
material,
true,
EdgePlacement$.MODULE$);
AdditionPlacement placement = assertInstanceOf(AdditionPlacement.class, even.apply());
assertEquals(POST_POS.copy().offset(1), placement.pos());
assertInstanceOf(PostMicroblock.class, placement.part());
assertSame(PostMicroClass$.MODULE$, placement.part().microClass());
assertEquals(2, placement.part().getSize());
assertEquals(0, placement.part().getShape());
}
@Test
void edgeCustomPlacementExpandsAMatchingPostInPlace() {
Microblock original = PostMicroClass$.MODULE$.create(false, material);
original.setShape(2, 0);
TileMultipart tile = TileMultipart.addPart(world, POST_EXPAND_POS, original);
MicroblockPlacement decision = new MicroblockPlacement(
player,
indexedHit(POST_EXPAND_POS, 0.25, 0),
2,
material,
true,
EdgePlacement$.MODULE$);
ExpandingPlacement placement = assertInstanceOf(ExpandingPlacement.class, decision.apply());
assertTrue(decision.internal());
assertTrue(decision.doExpand());
assertEquals(4, placement.part().getSize());
assertEquals(0, placement.part().getShape());
placement.place(world, player, new ItemStack(net.minecraft.init.Items.stick));
assertSame(original, tile.jPartList().get(0));
assertEquals(4, original.getSize());
assertEquals(0, original.getShape());
}
private Microblock face(int size, int slot) {
Microblock part = FaceMicroClass$.MODULE$.create(false, material);
part.setShape(size, slot);
return part;
}
private static int slot(Microblock part) {
return ((CommonMicroblock) part).getSlot();
}
private static MovingObjectPosition hit(BlockCoord pos, double relativeY) {
return new MovingObjectPosition(
pos.x,
pos.y,
pos.z,
1,
Vec3.createVectorHelper(pos.x + 0.5, pos.y + relativeY, pos.z + 0.5));
}
private static ExtendedMOP indexedHit(BlockCoord pos, double relativeY, int index) {
return new ExtendedMOP(
pos.x,
pos.y,
pos.z,
1,
Vec3.createVectorHelper(pos.x + 0.5, pos.y + relativeY, pos.z + 0.5),
new Tuple2<Object, Object>(index, null));
}
private void clearPositions() {
clear(EXTERNAL_POS);
clear(EXTERNAL_POS.copy().offset(1));
clear(INTERNAL_POS);
clear(EXPAND_POS);
clear(CUSTOM_POS);
clear(POST_POS);
clear(POST_POS.copy().offset(1));
clear(POST_EXPAND_POS);
}
private void clear(BlockCoord pos) {
world.removeTileEntity(pos.x, pos.y, pos.z);
world.setBlockToAir(pos.x, pos.y, pos.z);
}
}
@@ -0,0 +1,105 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.List;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraftforge.oredict.OreDictionary;
import org.junit.jupiter.api.Test;
import codechicken.microblock.MicroRecipe$;
import codechicken.microblock.handler.MicroblockProxy;
import codechicken.microblock.handler.MicroblockProxy$;
import codechicken.microblock.handler.MicroblockProxy_clientImpl;
import codechicken.microblock.handler.MicroblockProxy_serverImpl;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.registry.GameRegistry;
import scala.collection.Iterator;
class MicroblockProxyFunctionalTest {
@Test
void dedicatedServerStripsClientLifecycleAndResolvesTheCompanionToServerMethods() throws Exception {
assertSame(MicroblockProxy$.MODULE$, MicroblockProxy$.class.getField("MODULE$").get(null));
assertThrows(NoSuchMethodError.class, () -> MicroblockProxy.init());
assertThrows(NoSuchMethodError.class, () -> MicroblockProxy.postInit());
assertThrows(NoClassDefFoundError.class, () -> MicroblockProxy_clientImpl.class.getDeclaredMethods());
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle init = lookup.findVirtual(MicroblockProxy$.class, "init", MethodType.methodType(void.class));
MethodHandle postInit = lookup
.findVirtual(MicroblockProxy$.class, "postInit", MethodType.methodType(void.class));
assertSame(MicroblockProxy_serverImpl.class, lookup.revealDirect(init).getDeclaringClass());
assertSame(MicroblockProxy_serverImpl.class, lookup.revealDirect(postInit).getDeclaringClass());
assertNotNull(MicroblockProxy.itemMicro());
assertNotNull(MicroblockProxy.sawStone());
assertNotNull(MicroblockProxy.sawIron());
assertNotNull(MicroblockProxy.sawDiamond());
assertNotNull(MicroblockProxy.stoneRod());
assertEquals(3, MicroblockProxy$.MODULE$.saws().size());
}
@Test
void registersItemsOreSawOrderAndRecipes() {
assertFalse(Loader.isModLoaded("dreamcraft"));
assertSame(MicroblockProxy.itemMicro(), GameRegistry.findItem("ForgeMicroblock", "microblock"));
assertSame(MicroblockProxy.sawStone(), GameRegistry.findItem("ForgeMicroblock", "sawStone"));
assertSame(MicroblockProxy.sawIron(), GameRegistry.findItem("ForgeMicroblock", "sawIron"));
assertSame(MicroblockProxy.sawDiamond(), GameRegistry.findItem("ForgeMicroblock", "sawDiamond"));
assertSame(MicroblockProxy.stoneRod(), GameRegistry.findItem("ForgeMicroblock", "stoneRod"));
assertTrue(containsItem(OreDictionary.getOres("rodStone"), MicroblockProxy.stoneRod()));
Iterator<Item> saws = MicroblockProxy$.MODULE$.saws().iterator();
assertSame(MicroblockProxy.sawStone(), saws.next());
assertSame(MicroblockProxy.sawIron(), saws.next());
assertSame(MicroblockProxy.sawDiamond(), saws.next());
assertFalse(saws.hasNext());
@SuppressWarnings("unchecked")
List<IRecipe> recipes = CraftingManager.getInstance().getRecipeList();
int microRecipe = recipes.indexOf(MicroRecipe$.MODULE$);
int stoneRod = recipeIndex(recipes, MicroblockProxy.stoneRod(), 4);
int sawStone = recipeIndex(recipes, MicroblockProxy.sawStone(), 1);
int sawIron = recipeIndex(recipes, MicroblockProxy.sawIron(), 1);
int sawDiamond = recipeIndex(recipes, MicroblockProxy.sawDiamond(), 1);
assertTrue(microRecipe >= 0);
assertTrue(stoneRod >= 0);
assertTrue(sawStone >= 0);
assertTrue(sawIron >= 0);
assertTrue(sawDiamond >= 0);
}
private static boolean containsItem(List<ItemStack> stacks, Item item) {
for (ItemStack stack : stacks) {
if (stack.getItem() == item) {
return true;
}
}
return false;
}
private static int recipeIndex(List<IRecipe> recipes, Item item, int stackSize) {
for (int index = 0; index < recipes.size(); index++) {
ItemStack output = recipes.get(index).getRecipeOutput();
if (output != null && output.getItem() == item && output.stackSize == stackSize) {
return index;
}
}
return -1;
}
}
@@ -0,0 +1,87 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import codechicken.microblock.CommonMicroblock;
import codechicken.microblock.FaceMicroClass$;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.Microblock;
import codechicken.microblock.MicroblockClient;
import codechicken.microblock.MicroblockClient$class;
import codechicken.microblock.MicroblockGenerator;
class MicroblockTraitsFunctionalTest {
@Test
void generatedCommonTraitUsesMaterialShapeBoundsAndClass() {
int material = MicroMaterialRegistry.materialID("minecraft:stone");
Microblock part = MicroblockGenerator.create(FaceMicroClass$.MODULE$, material, false);
CommonMicroblock common = (CommonMicroblock) part;
assertFalse(part instanceof MicroblockClient);
assertEquals(material, part.material());
assertEquals(0, part.shape());
for (int side = 0; side < 6; side++) {
part.setShape(3, side);
assertEquals(side, common.getSlot());
assertEquals(1 << side, common.getSlotMask());
assertSame(FaceMicroClass$.MODULE$, common.microClass());
assertEquals(FaceMicroClass$.MODULE$.getClassId(), part.itemClassID());
assertEquals(1, common.getPartialOcclusionBoxes().size());
assertSame(part.getBounds(), common.getPartialOcclusionBoxes().get(0));
}
}
@Test
void absentMaterialReachesTheClientOnlyStoneLookupOnTheServer() {
// getBrokenIcon only needs the Microblock base cast; a proxy would not satisfy that contract.
MissingMaterialClient part = new MissingMaterialClient();
for (int side : new int[] { -1, 0, 5, 12 }) {
// Forge strips Block.getIcon on a dedicated server; reaching it proves the fallback was selected.
NoSuchMethodError error = assertThrows(
NoSuchMethodError.class,
() -> MicroblockClient$class.getBrokenIcon(part, side));
assertTrue(error.getMessage().contains("net.minecraft.block.Block.getIcon(II)"));
}
assertEquals(4, part.materialReads);
}
private static final class MissingMaterialClient extends Microblock implements MicroblockClient {
int materialReads;
MissingMaterialClient() {
super(-1);
}
@Override
public codechicken.microblock.MicroMaterialRegistry.IMicroMaterial getIMaterial() {
materialReads++;
return null;
}
@Override
public codechicken.microblock.MicroblockClass microClass() {
return FaceMicroClass$.MODULE$;
}
@Override
public int itemClassID() {
return 0;
}
@Override
public codechicken.lib.vec.Cuboid6 getBounds() {
return codechicken.lib.vec.Cuboid6.full;
}
@Override
public net.minecraft.util.IIcon getBrokenIcon(int side) {
return MicroblockClient$class.getBrokenIcon(this, side);
}
@Override
public void render(codechicken.lib.vec.Vector3 pos, int pass) {}
}
}
@@ -0,0 +1,53 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import org.junit.jupiter.api.Test;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.MissingMicroMaterial;
import codechicken.microblock.MissingMicroMaterial$;
class MissingMicroMaterialFunctionalTest {
private static final Set<String> CLIENT_METHODS = Arrays
.stream(new String[] { "getBreakingIcon", "loadIcons", "renderMicroFace" }).collect(Collectors.toSet());
@Test
void dedicatedServerRegistersTheCompanionAfterStrippingClientState() {
assertSame(MissingMicroMaterial$.MODULE$, MicroMaterialRegistry.getMaterial(MissingMicroMaterial.key()));
assertSame(
MissingMicroMaterial$.MODULE$,
MicroMaterialRegistry.getMaterial(MicroMaterialRegistry.getMissingId()));
ItemStack item = MissingMicroMaterial$.MODULE$.getItem();
assertSame(Item.getItemFromBlock(Blocks.stone), item.getItem());
assertEquals(1, item.stackSize);
assertEquals(0, item.getItemDamage());
assertFalse(publicMethodNames(MissingMicroMaterial.class).stream().anyMatch(CLIENT_METHODS::contains));
assertFalse(publicMethodNames(MissingMicroMaterial$.class).stream().anyMatch(CLIENT_METHODS::contains));
assertFalse(
Arrays.stream(MissingMicroMaterial$.class.getDeclaredFields())
.filter(field -> !Modifier.isStatic(field.getModifiers())).map(Field::getName)
.anyMatch("icon"::equals));
}
private static Set<String> publicMethodNames(Class<?> type) {
return Arrays.stream(type.getDeclaredMethods()).filter(method -> Modifier.isPublic(method.getModifiers()))
.map(Method::getName).collect(Collectors.toSet());
}
}
@@ -0,0 +1,376 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.*;
import static org.objectweb.asm.Opcodes.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import codechicken.lib.asm.ASMHelper;
import codechicken.multipart.asm.ASMMixinCompiler$;
import codechicken.multipart.asm.ASMMixinCompiler.ClassInfo;
import codechicken.multipart.asm.ASMMixinCompiler.FieldMixin;
import codechicken.multipart.asm.ASMMixinCompiler.MixinInfo;
import codechicken.multipart.asm.DebugPrinter$;
import scala.collection.JavaConversions;
import scala.collection.Seq;
import scala.collection.mutable.Map;
class MixinClassesFunctionalTest {
static final ASMMixinCompiler$ COMPILER = ASMMixinCompiler$.MODULE$;
static final String PREFIX = "codechicken/multipart/test/composition/";
@Test
void emptyTraitsResolveTheBaseAndIgnoreTheGeneratedName() throws Exception {
try (Scope scope = new Scope()) {
Class<?> base = scope.define(base("EmptyBase"));
assertSame(base, COMPILER.mixinClasses(null, Type.getInternalName(base), seq()));
assertSame(base, COMPILER.mixinClasses("ignored", base.getName(), seq()));
assertFalse(scope.bytes.contains("ignored"));
}
}
@Test
void diamondParentsInitializeOnceAndSuperCallsFollowLinearization() throws Exception {
try (Scope scope = new Scope()) {
ClassNode base = base("DiamondBase");
scope.define(base);
MixinInfo parent = scope.trait("Parent", base.name, seq(), 1);
MixinInfo left = scope.trait("Left", base.name, seq(parent), 10);
MixinInfo right = scope.trait("Right", base.name, seq(parent), 100);
Object value = COMPILER.mixinClasses(PREFIX + "Diamond", base.name, seq(left.name(), right.name()))
.getConstructor(int.class).newInstance(7);
assertEquals("BParentLeftRight", value.getClass().getField("trace").get(value));
assertEquals(118, value.getClass().getMethod("score").invoke(value));
assertEquals("Right", value.getClass().getMethod("winner").invoke(value));
assertEquals(
Arrays.asList(left.name().replace('/', '.'), right.name().replace('/', '.')),
Arrays.asList(
value.getClass().getInterfaces()[0].getName(),
value.getClass().getInterfaces()[1].getName()));
Object reversed = COMPILER.mixinClasses(PREFIX + "Reversed", base.name, seq(right.name(), left.name()))
.getConstructor(int.class).newInstance(3);
assertEquals("BParentRightLeft", reversed.getClass().getField("trace").get(reversed));
assertEquals(114, reversed.getClass().getMethod("score").invoke(reversed));
assertEquals("Left", reversed.getClass().getMethod("winner").invoke(reversed));
}
}
@Test
void selectedConstructorForwardsArgumentsAndDoesNotCopyExceptionsOrOtherOverloads() throws Exception {
try (Scope scope = new Scope()) {
ClassNode base = base("ConstructorBase");
scope.define(base);
MixinInfo trait = scope.trait("ConstructorTrait", base.name, seq(), 2);
Class<?> result = COMPILER.mixinClasses(PREFIX + "Constructor", base.name, seq(trait.name()));
assertEquals(1, result.getDeclaredConstructors().length);
assertArrayEquals(new Class<?>[0], result.getConstructor(int.class).getExceptionTypes());
Object value = result.getConstructor(int.class).newInstance(41);
assertEquals(43, result.getMethod("score").invoke(value));
assertThrows(NoSuchMethodException.class, result::getConstructor);
}
}
@Test
void fieldsRetainPrivateStorageMangledAccessorsAndNarrowValueCategories() throws Exception {
try (Scope scope = new Scope()) {
ClassNode base = base("FieldsBase");
scope.define(base);
FieldMixin[] fields = { new FieldMixin("flag", "Z", ACC_PUBLIC), new FieldMixin("byteValue", "B", 0),
new FieldMixin("shortValue", "S", 0), new FieldMixin("charValue", "C", 0),
new FieldMixin("integer", "I", ACC_PRIVATE), new FieldMixin("real", "F", 0),
new FieldMixin("object", "Ljava/lang/Object;", 0), new FieldMixin("array", "[I", 0) };
MixinInfo trait = scope.trait("FieldsTrait", base.name, seq(), 1, fields);
Class<?> result = COMPILER.mixinClasses(PREFIX + "Fields", base.name, seq(trait.name()));
Object first = result.getConstructor(int.class).newInstance(0);
Object second = result.getConstructor(int.class).newInstance(0);
Object marker = new Object();
Object[] values = { true, (byte) -12, (short) 1234, '\u03bb', -99, 1.25F, marker, new int[] { 2, 7 } };
Class<?>[] types = { boolean.class, byte.class, short.class, char.class, int.class, float.class,
Object.class, int[].class };
for (int i = 0; i < fields.length; i++) {
String name = fields[i].accessName(trait.name());
assertEquals(Modifier.PRIVATE, result.getDeclaredField(name).getModifiers());
Method setter = result.getMethod(name + "_$eq", types[i]);
Method getter = result.getMethod(name);
Object initial = getter.invoke(second);
setter.invoke(first, values[i]);
assertEquals(values[i], getter.invoke(first));
assertEquals(initial, getter.invoke(second));
}
assertThrows(NoSuchMethodException.class, () -> result.getMethod("integer"));
}
}
@Test
void wideFieldGettersRetainTheExistingStackOverflowVerificationFailure() throws Exception {
for (String descriptor : Arrays.asList("J", "D")) {
try (Scope scope = new Scope()) {
ClassNode base = base("WideBase" + descriptor);
scope.define(base);
MixinInfo trait = scope
.trait("WideTrait" + descriptor, base.name, seq(), 1, new FieldMixin("wide", descriptor, 0));
Class<?> generated = COMPILER.mixinClasses(PREFIX + "Wide" + descriptor, base.name, seq(trait.name()));
VerifyError failure = assertThrows(VerifyError.class, () -> generated.getConstructor(int.class));
assertTrue(failure.getMessage().contains("Operand stack overflow"));
ClassNode output = COMPILER.classNode(PREFIX + "Wide" + descriptor);
MethodNode getter = (MethodNode) output.methods.stream()
.filter(m -> ((MethodNode) m).name.equals("wide")).findFirst().get();
assertEquals(1, getter.maxStack);
}
}
}
@Test
void covariantBridgeDispatchesToTheWinningTraitAndKeepsItsOwnExceptions() throws Exception {
try (Scope scope = new Scope()) {
ClassNode base = base("CovariantBase");
MethodVisitor value = base.visitMethod(
ACC_PUBLIC,
"winner",
"()Ljava/lang/Object;",
null,
new String[] { "java/io/IOException" });
value.visitLdcInsn("base");
value.visitInsn(ARETURN);
value.visitMaxs(1, 1);
Class<?> baseClass = scope.define(base);
MixinInfo trait = scope.trait("CovariantTrait", base.name, seq(), 1);
Class<?> result = COMPILER.mixinClasses(PREFIX + "Covariant", base.name, seq(trait.name()));
Object instance = result.getConstructor(int.class).newInstance(0);
assertEquals("CovariantTrait", baseClass.getMethod("winner").invoke(instance));
Method bridge = Arrays.stream(result.getDeclaredMethods()).filter(Method::isBridge).findFirst().get();
assertTrue(bridge.isSynthetic());
assertEquals(Object.class, bridge.getReturnType());
assertArrayEquals(new Class<?>[] { java.io.IOException.class }, bridge.getExceptionTypes());
assertArrayEquals(
new Class<?>[] { IllegalStateException.class },
result.getMethod("winner").getExceptionTypes());
}
}
@Test
void missingMixinFailsBeforeBaseLookupAndMissingConstructorBeforeDefinition() throws Exception {
try (Scope scope = new Scope()) {
java.util.NoSuchElementException missing = assertThrows(
java.util.NoSuchElementException.class,
() -> COMPILER.mixinClasses(PREFIX + "Missing", "missing/base", seq("missing/trait")));
assertTrue(missing.getMessage().contains("missing/trait"));
assertFalse(scope.info.contains("missing/base"));
ClassNode base = base("NoConstructorBase");
base.methods.clear();
scope.define(base);
MixinInfo trait = scope.trait("NoConstructorTrait", base.name, seq(), 1);
assertEquals(
"None.get",
assertThrows(
java.util.NoSuchElementException.class,
() -> COMPILER.mixinClasses(PREFIX + "NoConstructor", base.name, seq(trait.name())))
.getMessage());
assertFalse(scope.bytes.contains(PREFIX + "NoConstructor"));
}
}
@Test
void missingSuperFailsBeforeDefinitionButDuplicateInterfacesReachTheJvmAndCache() throws Exception {
try (Scope scope = new Scope()) {
ClassNode base = base("FailureBase");
scope.define(base);
MixinInfo trait = scope.trait("FailureTrait", base.name, seq(), 1);
MixinInfo invalid = new MixinInfo(
trait.name(),
trait.parent(),
trait.parentTraits(),
trait.fields(),
trait.methods(),
seq("absent()I"));
scope.mixins.put(trait.name(), invalid);
assertEquals(
"None.get",
assertThrows(
java.util.NoSuchElementException.class,
() -> COMPILER.mixinClasses(PREFIX + "MissingSuper", base.name, seq(trait.name())))
.getMessage());
assertFalse(scope.bytes.contains(PREFIX + "MissingSuper"));
scope.mixins.put(trait.name(), trait);
InvocationTargetException failure = assertThrows(
InvocationTargetException.class,
() -> COMPILER.mixinClasses(PREFIX + "Duplicate", base.name, seq(trait.name(), trait.name())));
assertInstanceOf(ClassFormatError.class, failure.getCause());
assertTrue(scope.bytes.contains(PREFIX + "Duplicate"));
assertEquals(
Arrays.asList(trait.name(), trait.name()),
COMPILER.classNode(PREFIX + "Duplicate").interfaces);
}
}
static ClassNode base(String suffix) {
ClassNode node = node(PREFIX + suffix, "java/lang/Object", ACC_PUBLIC);
node.visitField(ACC_PUBLIC, "trace", "Ljava/lang/String;", null, null);
node.visitField(ACC_PUBLIC, "seed", "I", null, null);
MethodVisitor constructor = node
.visitMethod(ACC_PUBLIC, "<init>", "(I)V", null, new String[] { "java/io/IOException" });
constructor.visitVarInsn(ALOAD, 0);
constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
constructor.visitVarInsn(ALOAD, 0);
constructor.visitLdcInsn("B");
constructor.visitFieldInsn(PUTFIELD, node.name, "trace", "Ljava/lang/String;");
constructor.visitVarInsn(ALOAD, 0);
constructor.visitVarInsn(ILOAD, 1);
constructor.visitFieldInsn(PUTFIELD, node.name, "seed", "I");
constructor.visitInsn(RETURN);
constructor.visitMaxs(2, 2);
MethodVisitor empty = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
empty.visitVarInsn(ALOAD, 0);
empty.visitInsn(ICONST_0);
empty.visitMethodInsn(INVOKESPECIAL, node.name, "<init>", "(I)V", false);
empty.visitInsn(RETURN);
empty.visitMaxs(2, 1);
MethodVisitor score = node.visitMethod(ACC_PUBLIC, "score", "()I", null, null);
score.visitVarInsn(ALOAD, 0);
score.visitFieldInsn(GETFIELD, node.name, "seed", "I");
score.visitInsn(IRETURN);
score.visitMaxs(1, 1);
return node;
}
static ClassNode node(String name, String parent, int access) {
ClassNode node = new ClassNode();
node.visit(V1_6, access, name, null, parent, null);
return node;
}
@SafeVarargs
static <T> Seq<T> seq(T... values) {
return JavaConversions.asScalaBuffer(Arrays.asList(values)).toList();
}
static Field field(Class<?> owner, String name) throws Exception {
Field field = owner.getDeclaredField(name);
field.setAccessible(true);
return field;
}
static class Scope implements AutoCloseable {
final Field loaderField = field(ASMMixinCompiler$.class, "cl");
final Object previousLoader = loaderField.get(COMPILER);
final LaunchClassLoader loader = new LaunchClassLoader(new URL[0]) {
@Override
public Class<?> findClass(String name) throws ClassNotFoundException {
Class<?> loaded = findLoadedClass(name);
return loaded == null ? super.findClass(name) : loaded;
}
};
final Map<String, byte[]> bytes = cache("traitByteMap");
final Map<String, ClassInfo> info = cache("infoCache");
final Map<String, MixinInfo> mixins = cache("mixinMap");
final java.util.Map<String, byte[]> oldBytes = new HashMap<>(JavaConversions.mapAsJavaMap(bytes));
final java.util.Map<String, ClassInfo> oldInfo = new HashMap<>(JavaConversions.mapAsJavaMap(info));
final java.util.Map<String, MixinInfo> oldMixins = new HashMap<>(JavaConversions.mapAsJavaMap(mixins));
final Field debug = field(DebugPrinter$.class, "debug");
final boolean oldDebug = DebugPrinter$.MODULE$.debug();
final Field counter = field(DebugPrinter$.class, "permGenUsed");
final int oldCounter = counter.getInt(DebugPrinter$.MODULE$);
Scope() throws Exception {
loaderField.set(COMPILER, loader);
debug.setBoolean(DebugPrinter$.MODULE$, true);
}
Class<?> define(ClassNode node) {
return COMPILER.define(node.name, ASMHelper.createBytes(node, 0));
}
MixinInfo trait(String suffix, String base, Seq<MixinInfo> parents, int increment, FieldMixin... fields) {
String name = PREFIX + suffix;
ClassNode contract = node(name, "java/lang/Object", ACC_PUBLIC | ACC_INTERFACE | ACC_ABSTRACT);
for (MixinInfo parent : JavaConversions.seqAsJavaList(parents)) contract.interfaces.add(parent.name());
MethodNode score = (MethodNode) contract.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, "score", "()I", null, null);
MethodNode winner = (MethodNode) contract.visitMethod(
ACC_PUBLIC | ACC_ABSTRACT,
"winner",
"()Ljava/lang/String;",
null,
new String[] { "java/lang/IllegalStateException" });
String superName = name.replace('/', '$') + "$$super$score";
contract.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, superName, "()I", null, null);
for (FieldMixin f : fields) {
contract.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, f.accessName(name), "()" + f.desc(), null, null);
contract.visitMethod(
ACC_PUBLIC | ACC_ABSTRACT,
f.accessName(name) + "_$eq",
"(" + f.desc() + ")V",
null,
null);
}
define(contract);
ClassNode helper = node(name + "$class", "java/lang/Object", ACC_PUBLIC);
MethodVisitor init = helper.visitMethod(ACC_PUBLIC | ACC_STATIC, "$init$", "(L" + name + ";)V", null, null);
init.visitVarInsn(ALOAD, 0);
init.visitTypeInsn(CHECKCAST, base);
init.visitInsn(DUP);
init.visitFieldInsn(GETFIELD, base, "trace", "Ljava/lang/String;");
init.visitLdcInsn(suffix);
init.visitMethodInsn(
INVOKEVIRTUAL,
"java/lang/String",
"concat",
"(Ljava/lang/String;)Ljava/lang/String;",
false);
init.visitFieldInsn(PUTFIELD, base, "trace", "Ljava/lang/String;");
init.visitInsn(RETURN);
init.visitMaxs(3, 1);
MethodVisitor value = helper.visitMethod(ACC_PUBLIC | ACC_STATIC, "score", "(L" + name + ";)I", null, null);
value.visitVarInsn(ALOAD, 0);
value.visitMethodInsn(INVOKEINTERFACE, name, superName, "()I", true);
value.visitLdcInsn(increment);
value.visitInsn(IADD);
value.visitInsn(IRETURN);
value.visitMaxs(2, 1);
MethodVisitor winning = helper
.visitMethod(ACC_PUBLIC | ACC_STATIC, "winner", "(L" + name + ";)Ljava/lang/String;", null, null);
winning.visitLdcInsn(suffix);
winning.visitInsn(ARETURN);
winning.visitMaxs(1, 1);
define(helper);
MixinInfo result = new MixinInfo(name, base, parents, seq(fields), seq(score, winner), seq("score()I"));
mixins.put(name, result);
return result;
}
@SuppressWarnings("unchecked")
private <T> Map<String, T> cache(String name) throws Exception {
return (Map<String, T>) field(ASMMixinCompiler$.class, name).get(COMPILER);
}
@Override
public void close() throws Exception {
loaderField.set(COMPILER, previousLoader);
debug.setBoolean(DebugPrinter$.MODULE$, oldDebug);
counter.setInt(DebugPrinter$.MODULE$, oldCounter);
bytes.clear();
oldBytes.forEach(bytes::put);
info.clear();
oldInfo.forEach(info::put);
mixins.clear();
oldMixins.forEach(mixins::put);
loader.close();
}
}
}
@@ -0,0 +1,61 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Locale;
import net.minecraft.block.Block;
import net.minecraft.world.World;
import org.junit.jupiter.api.Test;
import codechicken.multipart.handler.MCPCCompatModule;
import codechicken.multipart.handler.MultipartCompatiblity;
import cpw.mods.fml.common.FMLCommonHandler;
import scala.Function4;
import scala.runtime.AbstractFunction4;
class MultipartCompatiblityFunctionalTest {
@Test
void loadLeavesTheCallbackUntouchedOutsideMcpc() {
assertFalse(FMLCommonHandler.instance().getModName().toLowerCase(Locale.ROOT).contains("mcpc"));
Function4<World, Object, Object, Object, Object> original = MultipartCompatiblity.canAddPart();
Function4<World, Object, Object, Object, Object> replacement = new DenyPlacement();
try {
MultipartCompatiblity.canAddPart_$eq(replacement);
MultipartCompatiblity.load();
assertSame(replacement, MultipartCompatiblity.canAddPart());
} finally {
MultipartCompatiblity.canAddPart_$eq(original);
}
}
@Test
void missingMcpcHookIsLoggedAndLeavesTheCallbackUntouched() {
assertThrows(
NoSuchMethodException.class,
() -> World.class.getDeclaredMethod("canPlaceMultipart", Block.class, int.class, int.class, int.class));
Function4<World, Object, Object, Object, Object> original = MultipartCompatiblity.canAddPart();
Function4<World, Object, Object, Object, Object> replacement = new DenyPlacement();
try {
MultipartCompatiblity.canAddPart_$eq(replacement);
// The absent hook is reported at ERROR; that is the behaviour under test.
ExpectedErrorLog.silence(() -> assertDoesNotThrow(MCPCCompatModule::load));
assertSame(replacement, MultipartCompatiblity.canAddPart());
} finally {
MultipartCompatiblity.canAddPart_$eq(original);
}
}
private static final class DenyPlacement extends AbstractFunction4<World, Object, Object, Object, Object> {
@Override
public Object apply(World world, Object x, Object y, Object z) {
return Boolean.FALSE;
}
}
}
@@ -0,0 +1,130 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.ChunkCoordIntPair;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraft.world.chunk.Chunk;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.common.util.FakePlayerFactory;
import net.minecraftforge.event.world.ChunkDataEvent;
import net.minecraftforge.event.world.ChunkWatchEvent;
import net.minecraftforge.event.world.WorldEvent;
import org.junit.jupiter.api.Test;
import codechicken.lib.vec.BlockCoord;
import codechicken.multipart.handler.MultipartEventHandler;
import codechicken.multipart.handler.MultipartEventHandler$;
import codechicken.multipart.handler.MultipartSPH$;
import codechicken.multipart.handler.MultipartSaveLoad;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.EventBus;
import cpw.mods.fml.common.gameevent.TickEvent;
class MultipartEventHandlerFunctionalTest {
@Test
void bothEventBusesUseTheCompanionIdentity() throws Exception {
assertSame(MultipartEventHandler$.MODULE$, registeredCompanion(FMLCommonHandler.instance().bus()));
assertSame(MultipartEventHandler$.MODULE$, registeredCompanion(MinecraftForge.EVENT_BUS));
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
void chunkLoadAndWorldUnloadMaintainTransientServerState() {
WorldServer world = world();
World originalLoadingWorld = MultipartSaveLoad.loadingWorld();
scala.collection.mutable.Map updates = MultipartSPH$.MODULE$
.codechicken$multipart$handler$MultipartSPH$$updateMap();
try {
MultipartSaveLoad.loadingWorld_$eq(null);
Chunk chunk = new Chunk(world, 75, 75);
MultipartEventHandler.tileEntityLoad(new ChunkDataEvent.Load(chunk, new NBTTagCompound()));
assertSame(world, MultipartSaveLoad.loadingWorld());
MultipartSPH$.MODULE$.getTileStream(world, new BlockCoord(1200, 70, 1200));
assertTrue(updates.contains(world));
MultipartEventHandler.worldUnLoad(new WorldEvent.Unload(world));
assertNull(MultipartSaveLoad.loadingWorld());
assertFalse(updates.contains(world));
} finally {
updates.remove(world);
MultipartSaveLoad.loadingWorld_$eq(originalLoadingWorld);
}
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
void watchChangesAreAppliedOnlyAtTheEndOfTheServerTick() {
WorldServer world = world();
FakePlayer player = FakePlayerFactory.getMinecraft(world);
assertNotNull(player);
player.setEntityId(-123456789);
Integer playerId = player.getEntityId();
ChunkCoordIntPair chunk = new ChunkCoordIntPair(0, 0);
scala.collection.mutable.Map newWatchers = MultipartSPH$.MODULE$
.codechicken$multipart$handler$MultipartSPH$$newWatchers();
scala.collection.mutable.HashMap chunkWatchers = MultipartSPH$.MODULE$
.codechicken$multipart$handler$MultipartSPH$$chunkWatchers();
List<EntityPlayerMP> players = MinecraftServer.getServer().getConfigurationManager().playerEntityList;
newWatchers.remove(playerId);
chunkWatchers.remove(playerId);
players.add(player);
try {
MultipartEventHandler.chunkWatch(new ChunkWatchEvent.Watch(chunk, player));
assertTrue(newWatchers.contains(playerId));
MultipartEventHandler.serverTick(new TickEvent.ServerTickEvent(TickEvent.Phase.START));
assertTrue(newWatchers.contains(playerId));
assertFalse(chunkWatchers.contains(playerId));
MultipartEventHandler.serverTick(new TickEvent.ServerTickEvent(TickEvent.Phase.END));
assertFalse(newWatchers.contains(playerId));
assertTrue(((scala.collection.Set) chunkWatchers.apply(playerId)).contains(chunk));
MultipartEventHandler.chunkUnWatch(new ChunkWatchEvent.UnWatch(chunk, player));
assertFalse(chunkWatchers.contains(playerId));
} finally {
players.remove(player);
newWatchers.remove(playerId);
chunkWatchers.remove(playerId);
}
}
private static Object registeredCompanion(EventBus bus) throws Exception {
Field listenersField = EventBus.class.getDeclaredField("listeners");
listenersField.setAccessible(true);
Map<?, ?> listeners = (Map<?, ?>) listenersField.get(bus);
for (Object target : listeners.keySet()) {
if (target == MultipartEventHandler$.MODULE$) {
return target;
}
}
return null;
}
private static WorldServer world() {
WorldServer world = MinecraftServer.getServer().worldServers[0];
assertNotNull(world);
assertFalse(world.isRemote);
return world;
}
}
@@ -0,0 +1,319 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.BitSet;
import java.util.Collections;
import java.util.Objects;
import java.util.Scanner;
import net.minecraft.init.Blocks;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import org.junit.jupiter.api.Test;
import codechicken.lib.vec.BlockCoord;
import codechicken.multipart.MultipartGenerator;
import codechicken.multipart.MultipartGenerator$;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TSlottedPart;
import codechicken.multipart.TileCache;
import codechicken.multipart.TileMultipart;
import codechicken.multipart.TileMultipartClient;
import codechicken.multipart.asm.MultipartMixinFactory;
import codechicken.multipart.handler.MultipartProxy;
import codechicken.multipart.handler.MultipartSaveLoad;
import codechicken.multipart.minecraft.TorchPart;
import codechicken.multipart.scalatraits.TSlottedTile;
import scala.collection.JavaConversions;
import scala.collection.Seq;
import scala.collection.mutable.Map;
public class MultipartGeneratorFunctionalTest {
@Test
void cachesCompleteHierarchySeparatelyPerSideAndKeepsFirstRegistration() {
MultipartGenerator$ generator = MultipartGenerator$.MODULE$;
String root = RootMarker.class.getName();
String slotted = "codechicken.multipart.scalatraits.TSlottedTile";
String redstone = "codechicken.multipart.scalatraits.TRedstoneTile";
String tileChange = "codechicken.multipart.scalatraits.TTileChangeTile";
MultipartGenerator.registerTrait(root, redstone, slotted);
HierarchyPart part = new HierarchyPart();
BitSet server = generator.codechicken$multipart$MultipartGenerator$$traitsForPart(part, false);
BitSet client = generator.codechicken$multipart$MultipartGenerator$$traitsForPart(part, true);
assertEquals(bits(slotted), server);
assertEquals(bits(redstone), client);
assertNotSame(server, client);
assertSame(
server,
generator.codechicken$multipart$MultipartGenerator$$traitsForPart(new HierarchyPart(), false));
// Deliberate duplicate: both sides log at ERROR and keep the first registration.
ExpectedErrorLog.silence(() -> MultipartGenerator.registerTrait(root, slotted, redstone));
assertEquals(slotted.replace('.', '/'), map(false).apply(root.replace('.', '/')));
assertEquals(redstone.replace('.', '/'), map(true).apply(root.replace('.', '/')));
MultipartGenerator.registerTrait(LateMarker.class.getName(), tileChange, null);
assertSame(client, generator.codechicken$multipart$MultipartGenerator$$traitsForPart(part, true));
assertEquals(bits(redstone), client, "Late registration does not invalidate an already-cached part class");
BitSet fresh = bits(redstone, tileChange);
assertEquals(
fresh,
generator.codechicken$multipart$MultipartGenerator$$traitsForPart(new FreshHierarchyPart(), true));
assertEquals(
bits(slotted),
generator.codechicken$multipart$MultipartGenerator$$traitsForPart(new FreshHierarchyPart(), false));
String missing = "codechicken.multipart.test.NonexistentGeneratorTrait";
assertThrows(
ClassNotFoundException.class,
() -> MultipartGenerator.registerTrait(FailedMarker.class.getName(), null, missing));
assertEquals(
missing.replace('.', '/'),
map(false).apply(FailedMarker.class.getName().replace('.', '/')),
"The reference records a side mapping before resolving its trait class");
String passThrough = GeneratorPassThroughFixture.class.getName().replace('.', '/');
assertTrue(map(false).contains(passThrough));
assertFalse(map(true).contains(passThrough));
}
@Test
void reusesOnlyExactTraitSetsAndSnapshotsRegisteredClasses() {
MultipartGenerator$ generator = MultipartGenerator$.MODULE$;
BitSet registration = new BitSet();
generator.registerTileClass(RegisteredTile.class, registration);
registration.set(4095);
BitSet scratch = MultipartGenerator.getBitSet();
scratch.set(4095);
RegisteredTile registered = new RegisteredTile();
assertSame(registered, generator.generateCompositeTile(registered, parts(), false));
assertSame(scratch, MultipartGenerator.getBitSet());
assertTrue(scratch.isEmpty(), "Every construction clears the reused scratch set");
assertEquals("savedMultipart", MultipartSaveLoad.getClassToNameMap().get(RegisteredTile.class));
SlottedPart slotted = new SlottedPart();
TileMultipart plain = generator.generateCompositeTile(null, parts(), false);
assertSame(plain, generator.generateCompositeTile(plain, parts(new PlainPart()), false));
TileMultipart upgraded = generator.generateCompositeTile(plain, parts(slotted), false);
assertNotSame(plain, upgraded);
assertTrue(upgraded instanceof TSlottedTile);
assertSame(
upgraded,
generator.generateCompositeTile(upgraded, parts(slotted, new PlainPart(), slotted), false));
assertSame(
upgraded.getClass(),
generator.generateCompositeTile(null, parts(new PlainPart(), slotted), false).getClass());
TileMultipart client = generator.generateCompositeTile(upgraded, parts(slotted), true);
assertTrue(client instanceof TileMultipartClient);
assertNotSame(upgraded, client);
assertSame(client, generator.generateCompositeTile(client, parts(slotted), true));
assertThrows(
java.util.NoSuchElementException.class,
() -> generator.generateCompositeTile(new UnregisteredTile(), parts(), false));
}
@Test
void upgradesAndDowngradesLiveTilesWithoutLosingParts() {
World world = MinecraftServer.getServer().worldServers[0];
BlockCoord pos = new BlockCoord(48, 200, 48);
world.getChunkFromBlockCoords(pos.x, pos.z);
world.setBlockToAir(pos.x, pos.y, pos.z);
PlainPart first = new PlainPart();
SlottedPart second = new SlottedPart();
try {
TileMultipart plain = TileMultipart.addPart(world, pos, first);
TileMultipart upgraded = TileMultipart.addPart(world, pos, second);
assertNotSame(plain, upgraded);
assertTrue(plain.isInvalid());
assertTrue(upgraded instanceof TSlottedTile);
assertSame(upgraded, world.getTileEntity(pos.x, pos.y, pos.z));
assertEquals(Arrays.asList(first, second), upgraded.jPartList());
assertSame(upgraded, first.tile());
assertSame(second, upgraded.partMap(3));
TileMultipart downgraded = upgraded.remPart(second);
assertTrue(upgraded.isInvalid());
assertNotSame(upgraded, downgraded);
assertSame(plain.getClass(), downgraded.getClass());
assertSame(downgraded, world.getTileEntity(pos.x, pos.y, pos.z));
assertSame(downgraded, first.tile());
assertEquals(Collections.singletonList(first), downgraded.jPartList());
} finally {
world.setBlockToAir(pos.x, pos.y, pos.z);
}
}
@Test
void convertsVanillaBlockBeforeAppendingTheNewPart() {
World world = MinecraftServer.getServer().worldServers[0];
BlockCoord pos = new BlockCoord(50, 200, 48);
world.getChunkFromBlockCoords(pos.x, pos.z);
world.setBlock(pos.x, pos.y - 1, pos.z, Blocks.stone, 0, 0);
world.setBlock(pos.x, pos.y, pos.z, Blocks.torch, 5, 0);
PlainPart added = new PlainPart();
try {
TileMultipart tile = TileMultipart.addPart(world, pos, added);
assertSame(MultipartProxy.block(), world.getBlock(pos.x, pos.y, pos.z));
assertSame(tile, world.getTileEntity(pos.x, pos.y, pos.z));
assertEquals(2, tile.partList().size());
assertTrue(tile.partList().apply(0) instanceof TorchPart);
assertSame(added, tile.partList().apply(1));
assertSame(tile, tile.partList().apply(0).tile());
} finally {
world.setBlockToAir(pos.x, pos.y, pos.z);
world.setBlockToAir(pos.x, pos.y - 1, pos.z);
}
}
@Test
void clientAdditionsReplaceStaleConvertibleBlocksWithoutConvertingThem() {
World world = MinecraftServer.getServer().worldServers[0];
BlockCoord pos = new BlockCoord(51, 200, 48);
world.getChunkFromBlockCoords(pos.x, pos.z);
world.setBlock(pos.x, pos.y - 1, pos.z, Blocks.stone, 0, 0);
world.setBlock(pos.x, pos.y, pos.z, Blocks.torch, 5, 0);
boolean wasRemote = world.isRemote;
TileCache.FlaggedTile cached = TileCache.map().get(pos);
try {
// The server-started test event is synchronous; restore the side before any server tick.
world.isRemote = true;
PlainPart first = new PlainPart();
TileMultipart tile = MultipartGenerator$.MODULE$.addPart(world, pos, first);
assertTrue(tile instanceof TileMultipartClient);
assertSame(MultipartProxy.block(), world.getBlock(pos.x, pos.y, pos.z));
assertSame(tile, world.getTileEntity(pos.x, pos.y, pos.z));
assertEquals(Collections.singletonList(first), tile.jPartList());
assertSame(tile, first.tile());
PlainPart second = new PlainPart();
assertSame(tile, MultipartGenerator$.MODULE$.addPart(world, pos, second));
assertEquals(Arrays.asList(first, second), tile.jPartList());
assertSame(tile, second.tile());
} finally {
world.isRemote = wasRemote;
world.setBlockToAir(pos.x, pos.y, pos.z);
world.setBlockToAir(pos.x, pos.y - 1, pos.z);
if (cached == null) TileCache.map().remove(pos);
else TileCache.map().put(pos, cached);
}
}
@Test
void frozenScalaConsumerLinksCompanionGenerationAndDefaultPassThroughRegistration() throws Exception {
byte[] bytes;
try (InputStream stream = Objects.requireNonNull(
getClass().getResourceAsStream("/compat/ReferenceScalaMultipartGeneratorConsumer.class.b64"));
Scanner scanner = new Scanner(stream, StandardCharsets.UTF_8.name())) {
bytes = Base64.getMimeDecoder().decode(scanner.useDelimiter("\\A").next());
}
Class<?> type = new FixtureClassLoader(MultipartGenerator.class.getClassLoader()).define(bytes);
Object consumer = type.getDeclaredConstructor().newInstance();
type.getMethod("register", String.class).invoke(consumer, FrozenPassThrough.class.getName());
String key = FrozenPassThrough.class.getName().replace('.', '/');
assertTrue(map(false).contains(key));
assertEquals(map(false).apply(key), map(true).apply(key));
Seq<TMultiPart> parts = parts(new PassThroughPart());
TileMultipart tile = (TileMultipart) type
.getMethod("create", TileEntity.class, scala.collection.Iterable.class, boolean.class)
.invoke(consumer, null, parts, false);
tile.loadParts(parts);
assertEquals(37, ((FrozenPassThrough) tile).value());
}
private static Map<String, String> map(boolean client) {
return MultipartGenerator$.MODULE$.codechicken$multipart$MultipartGenerator$$interfaceTraitMap(client);
}
private static BitSet bits(String... names) {
BitSet bits = new BitSet();
for (String name : names) bits.set(MultipartMixinFactory.getId(name.replace('.', '/')));
return bits;
}
private static Seq<TMultiPart> parts(TMultiPart... parts) {
return JavaConversions.asScalaBuffer(Arrays.asList(parts)).toList();
}
public interface RootMarker {
}
public interface ChildMarker extends RootMarker {
}
public interface LateMarker {
}
public interface FailedMarker {
}
public interface FrozenPassThrough {
int value();
}
public static class PlainPart extends TMultiPart {
@Override
public String getType() {
return "mc_torch";
}
@Override
public boolean doesTick() {
return false;
}
}
public static class ParentPart extends PlainPart implements ChildMarker {
}
public static class HierarchyPart extends ParentPart implements LateMarker {
}
public static class FreshHierarchyPart extends HierarchyPart {
}
public static class SlottedPart extends PlainPart implements TSlottedPart {
@Override
public int getSlotMask() {
return 1 << 3;
}
}
public static class PassThroughPart extends PlainPart implements FrozenPassThrough {
@Override
public int value() {
return 37;
}
}
public static class RegisteredTile extends TileMultipart {
}
public static class UnregisteredTile extends TileMultipart {
}
private static final class FixtureClassLoader extends ClassLoader {
private FixtureClassLoader(ClassLoader parent) {
super(parent);
}
private Class<?> define(byte[] bytes) {
return defineClass(null, bytes, 0, bytes.length);
}
}
}
@@ -0,0 +1,214 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import org.junit.jupiter.api.Test;
import codechicken.lib.packet.PacketCustom;
import codechicken.multipart.MultiPartRegistry;
import codechicken.multipart.MultipartHelper;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TileMultipart;
import codechicken.multipart.TileMultipartClient;
import codechicken.multipart.examples.PartRegistrationExample;
import codechicken.multipart.examples.PartRegistrationExample.ExamplePart;
import codechicken.multipart.handler.MultipartSPH;
import codechicken.multipart.handler.MultipartSaveLoad;
import codechicken.multipart.minecraft.ButtonPart;
import codechicken.multipart.minecraft.TorchPart;
import io.netty.buffer.ByteBuf;
import scala.collection.JavaConversions;
/**
* The half of MultipartHelper a plain JVM test cannot reach. Tile construction runs the ASM generator, the NBT path
* needs the save/load hooks, and the packet path needs a loaded chunk.
*/
class MultipartHelperFunctionalTest {
@Test
void buildsATileAroundTheGivenParts() {
TMultiPart torch = MultiPartRegistry.loadPart("mc_torch", null);
assertNotNull(torch);
TileMultipart tile = MultipartHelper.createTileFromParts(Collections.singletonList(torch));
assertNotNull(tile);
assertEquals(1, tile.jPartList().size());
assertSame(torch, tile.jPartList().get(0));
assertSame(tile, torch.tile());
}
/**
* Multipart tiles all save themselves under the id "savedMultipart", which is the whole reason this entry point
* exists: the tile has to be rebuilt from NBT without waiting for the ChunkLoad event.
*/
@Test
void rebuildsAnOrderedSlottedTileFromItsOwnNbtAndPublishesTheLoadingWorld() {
World world = world();
TileMultipart saved = mixedTile();
NBTTagCompound tag = new NBTTagCompound();
saved.writeToNBT(tag);
assertEquals("savedMultipart", tag.getString("id"));
NBTTagList savedParts = tag.getTagList("parts", 10);
assertEquals(2, savedParts.tagCount());
assertEquals("mc_torch", savedParts.getCompoundTagAt(0).getString("id"));
assertEquals(5, savedParts.getCompoundTagAt(0).getByte("meta"));
assertEquals("mc_button", savedParts.getCompoundTagAt(1).getString("id"));
assertEquals(1, savedParts.getCompoundTagAt(1).getByte("meta"));
MultipartSaveLoad.loadingWorld_$eq(null);
TileEntity loaded = MultipartHelper.createTileFromNBT(world, tag);
TileMultipart tile = assertInstanceOf(TileMultipart.class, loaded);
assertEquals(2, tile.jPartList().size());
assertEquals("mc_torch", tile.jPartList().get(0).getType());
assertEquals("mc_button", tile.jPartList().get(1).getType());
assertSame(tile.jPartList().get(0), tile.partMap(0));
assertSame(tile.jPartList().get(1), tile.partMap(4));
assertSame(world, MultipartSaveLoad.loadingWorld());
}
@Test
void buildsAWorldlessClientPreviewFromSavedNbt() {
NBTTagCompound tag = previewTag(37);
TileMultipart tile = MultipartHelper.createPreviewTileFromNBT(null, tag);
assertTrue(tile instanceof TileMultipartClient);
assertNull(tile.getWorldObj());
assertEquals(31, tile.xCoord);
assertEquals(72, tile.yCoord);
assertEquals(-9, tile.zCoord);
assertEquals(1, tile.jPartList().size());
ExamplePart part = assertInstanceOf(ExamplePart.class, tile.jPartList().get(0));
assertSame(tile, part.tile());
assertEquals(37, part.value());
}
@Test
void rejectsServerWorldsBeforeConstructingPreviewParts() {
assertThrows(
IllegalArgumentException.class,
() -> MultipartHelper.createPreviewTileFromNBT(world(), previewTag(37)));
}
@Test
void writesTheExactMixedPartChunkDescriptionPacket() {
World world = world();
Chunk chunk = world.getChunkFromChunkCoords(1, 2);
TileMultipart tile = mixedTile();
tile.xCoord = 18;
tile.yCoord = 200;
tile.zCoord = 35;
PacketCustom packet = MultipartSPH.getDescPacket(chunk, Collections.<TileEntity>singletonList(tile).iterator());
ByteBuf buffer = packet.getByteBuf();
byte[] actual = new byte[buffer.writerIndex()];
buffer.getBytes(0, actual);
// type | chunk x/z | tile count | local x/y/z | part count | torch id/meta | button id/meta
assertArrayEquals(
new byte[] { 2, 0, 0, 0, 1, 0, 0, 0, 2, 0, 1, 2, 0, 0, 0, (byte) 200, 3, 2, 3, 5, 0, 1 },
actual);
}
/** The id guard runs before anything else, so a foreign tag must not disturb the loading world. */
@Test
void leavesTheLoadingWorldAloneForATagItDoesNotOwn() {
World world = world();
MultipartSaveLoad.loadingWorld_$eq(world);
NBTTagCompound tag = new NBTTagCompound();
tag.setString("id", "somethingElse");
assertNull(MultipartHelper.createTileFromNBT(null, tag));
assertSame(world, MultipartSaveLoad.loadingWorld());
}
@Test
void registersATileConverterOntoTheSaveLoadList() {
MarkerConverter converter = new MarkerConverter();
MultipartHelper.registerTileConverter(converter);
List<?> converters = JavaConversions.seqAsJavaList(MultipartSaveLoad.converters());
assertTrue(converters.contains(converter), "registerTileConverter must append to MultipartSaveLoad.converters");
}
/** Needs a loaded chunk. With no players watching, the send itself is a no-op, but the packet is still built. */
@Test
void sendsADescPacketForATileInALoadedChunk() {
World world = world();
TMultiPart torch = MultiPartRegistry.loadPart("mc_torch", null);
TileMultipart tile = MultipartHelper.createTileFromParts(Collections.singletonList(torch));
tile.setWorldObj(world);
tile.xCoord = 0;
tile.yCoord = 64;
tile.zCoord = 0;
assertNotNull(world.getChunkFromBlockCoords(0, 0));
assertDoesNotThrow(() -> MultipartHelper.sendDescPacket(world, tile));
}
private static World world() {
World world = MinecraftServer.getServer().worldServers[0];
assertNotNull(world);
return world;
}
private static TileMultipart mixedTile() {
return MultipartHelper.createTileFromParts(Arrays.asList(new TorchPart(5), new ButtonPart(1)));
}
private static NBTTagCompound previewTag(int value) {
NBTTagCompound part = new NBTTagCompound();
part.setString("id", PartRegistrationExample.PART_TYPE);
part.setInteger("value", value);
NBTTagList parts = new NBTTagList();
parts.appendTag(part);
NBTTagCompound tile = new NBTTagCompound();
tile.setString("id", "savedMultipart");
tile.setInteger("x", 31);
tile.setInteger("y", 72);
tile.setInteger("z", -9);
tile.setTag("parts", parts);
return tile;
}
/** Matches only its own tile class, so registering it cannot affect any real chunk load. */
private static final class MarkerTile extends TileEntity {
}
private static final class MarkerConverter extends MultipartHelper.IPartTileConverter<MarkerTile> {
MarkerConverter() {
super(MarkerTile.class);
}
@Override
public TMultiPart convertOne(MarkerTile tile) {
return null;
}
}
}
@@ -0,0 +1,145 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_TRANSIENT;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.GETFIELD;
import static org.objectweb.asm.Opcodes.IFEQ;
import static org.objectweb.asm.Opcodes.INSTANCEOF;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.NOP;
import static org.objectweb.asm.Opcodes.PUTFIELD;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V1_6;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
import codechicken.lib.asm.ASMHelper;
import codechicken.multipart.asm.MultipartMixinFactory$;
class MultipartMixinFactoryFunctionalTest {
private static final String TILE = "codechicken/multipart/TileMultipart";
private static final String COPY_DESC = "(L" + TILE + ";)V";
@Test
void leavesEmptyAndTransientOnlyTraitsUntouched() {
for (boolean transientField : new boolean[] { false, true }) {
ClassNode node = trait();
if (transientField) node.visitField(ACC_PUBLIC | ACC_TRANSIENT, "cache", "I", null, null);
byte[] before = ASMHelper.createBytes(node, 0);
MultipartMixinFactory$.MODULE$.autoCompleteJavaTrait(node);
assertEquals(0, node.methods.size());
assertArrayEquals(before, ASMHelper.createBytes(node, 0));
}
}
@Test
void preservesAnExistingCopyFromWithoutEmittingAnything() {
ClassNode node = trait();
node.visitField(ACC_PUBLIC, "saved", "I", null, null);
MethodNode existing = new MethodNode(ACC_PUBLIC, "copyFrom", COPY_DESC, null, null);
existing.visitInsn(NOP);
existing.visitInsn(RETURN);
existing.visitMaxs(0, 2);
node.methods.add(existing);
byte[] before = ASMHelper.createBytes(node, 0);
MultipartMixinFactory$.MODULE$.autoCompleteJavaTrait(node);
assertEquals(1, node.methods.size());
assertSame(existing, node.methods.get(0));
assertArrayEquals(before, ASMHelper.createBytes(node, 0));
}
@Test
void emitsSuperCallThenTypeGuardAndOnlyNonTransientFieldCopies() {
ClassNode node = trait();
node.visitField(ACC_PUBLIC, "first", "I", null, null);
node.visitField(ACC_PUBLIC | ACC_TRANSIENT, "cache", "I", null, null);
node.visitField(ACC_PUBLIC, "second", "Ljava/lang/String;", null, null);
MultipartMixinFactory$.MODULE$.autoCompleteJavaTrait(node);
assertEquals(1, node.methods.size());
MethodNode copy = node.methods.get(0);
assertEquals("copyFrom", copy.name);
assertEquals(COPY_DESC, copy.desc);
assertEquals(ACC_PUBLIC, copy.access);
assertEquals(2, copy.maxStack);
assertEquals(2, copy.maxLocals);
List<Integer> opcodes = new ArrayList<>();
List<Integer> locals = new ArrayList<>();
List<String> fields = new ArrayList<>();
for (AbstractInsnNode instruction : copy.instructions.toArray()) {
if (instruction.getOpcode() >= 0) opcodes.add(instruction.getOpcode());
if (instruction instanceof VarInsnNode) locals.add(((VarInsnNode) instruction).var);
if (instruction instanceof MethodInsnNode) {
MethodInsnNode call = (MethodInsnNode) instruction;
assertEquals(TILE, call.owner);
assertEquals("copyFrom", call.name);
assertEquals(COPY_DESC, call.desc);
}
if (instruction instanceof TypeInsnNode) {
assertEquals(node.name, ((TypeInsnNode) instruction).desc);
}
if (instruction instanceof JumpInsnNode) {
assertEquals(RETURN, ((JumpInsnNode) instruction).label.getNext().getOpcode());
}
if (instruction instanceof FieldInsnNode) {
FieldInsnNode field = (FieldInsnNode) instruction;
assertEquals(node.name, field.owner);
fields.add(field.name + ':' + field.desc);
}
}
assertEquals(
Arrays.asList(
ALOAD,
ALOAD,
INVOKESPECIAL,
ALOAD,
INSTANCEOF,
IFEQ,
ALOAD,
ALOAD,
GETFIELD,
PUTFIELD,
ALOAD,
ALOAD,
GETFIELD,
PUTFIELD,
RETURN),
opcodes);
assertEquals(Arrays.asList(0, 1, 1, 0, 1, 0, 1), locals);
assertEquals(
Arrays.asList("first:I", "first:I", "second:Ljava/lang/String;", "second:Ljava/lang/String;"),
fields);
byte[] before = ASMHelper.createBytes(node, 0);
MultipartMixinFactory$.MODULE$.autoCompleteJavaTrait(node);
assertArrayEquals(before, ASMHelper.createBytes(node, 0), "A second completion must not duplicate copyFrom");
}
private static ClassNode trait() {
ClassNode node = new ClassNode();
node.visit(V1_6, ACC_PUBLIC, "test/CopyFromFixture", null, TILE, null);
return node;
}
}
@@ -0,0 +1,57 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.World;
import org.junit.jupiter.api.Test;
import codechicken.multipart.ControlKeyModifer;
import codechicken.multipart.MultiPartRegistry;
import codechicken.multipart.handler.MultipartMod;
import codechicken.multipart.handler.MultipartMod$;
import codechicken.multipart.handler.MultipartProxy;
import codechicken.multipart.handler.MultipartSaveLoad;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
class MultipartModFunctionalTest {
@Test
void fmlUsesTheCompanionAndCompletesTheMultipartLifecycle() {
ModContainer container = Loader.instance().getIndexedModList().get("ForgeMultipart");
assertNotNull(container);
assertSame(MultipartMod$.MODULE$, container.getMod());
assertTrue(MultiPartRegistry.loaded());
assertNotNull(MultipartProxy.block());
assertNotNull(MultipartProxy.logger());
}
@Test
void serverStoppedClearsTransientWorldAndControlState() {
World originalWorld = MultipartSaveLoad.loadingWorld();
Map<EntityPlayer, Boolean> controls = ControlKeyModifer.map();
Map<EntityPlayer, Boolean> originalControls = new HashMap<>(controls);
try {
MultipartSaveLoad.loadingWorld_$eq(MinecraftServer.getServer().worldServers[0]);
controls.put(null, Boolean.TRUE);
MultipartMod.serverStopped(null);
assertNull(MultipartSaveLoad.loadingWorld());
assertTrue(controls.isEmpty());
} finally {
MultipartSaveLoad.loadingWorld_$eq(originalWorld);
controls.clear();
controls.putAll(originalControls);
}
}
}
@@ -0,0 +1,40 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import codechicken.multipart.handler.MultipartProxy;
import codechicken.multipart.handler.MultipartProxy$;
import codechicken.multipart.handler.MultipartProxy_clientImpl;
import codechicken.multipart.handler.MultipartProxy_serverImpl;
class MultipartProxyFunctionalTest {
@Test
void dedicatedServerStripsClientOverridesAndResolvesTheCompanionToServerMethods() throws Exception {
assertSame(MultipartProxy$.MODULE$, MultipartProxy$.class.getField("MODULE$").get(null));
assertEquals(0, MultipartProxy_clientImpl.class.getDeclaredMethods().length);
assertThrows(NoSuchMethodException.class, () -> MultipartProxy.class.getDeclaredMethod("postInit"));
assertThrows(
NoSuchMethodException.class,
() -> MultipartProxy.class.getDeclaredMethod("onTileClassBuilt", Class.class));
assertSame(MultipartProxy_serverImpl.class, MultipartProxy$.class.getMethod("postInit").getDeclaringClass());
assertSame(
MultipartProxy_serverImpl.class,
MultipartProxy$.class.getMethod("onTileClassBuilt", Class.class).getDeclaringClass());
assertSame(MultipartProxy_serverImpl.class, MultipartProxy$.class.getMethod("init").getDeclaringClass());
assertNotNull(MultipartProxy.block());
assertEquals("tile.multipart", MultipartProxy.block().getUnlocalizedName());
assertNotNull(MultipartProxy.config());
assertNotNull(MultipartProxy.logger());
assertSame(MultipartProxy.block(), MultipartProxy$.MODULE$.block());
assertSame(MultipartProxy.config(), MultipartProxy$.MODULE$.config());
assertSame(MultipartProxy.logger(), MultipartProxy$.MODULE$.logger());
}
}
@@ -0,0 +1,270 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.*;
import static org.objectweb.asm.Opcodes.*;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import net.minecraft.tileentity.TileEntity;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.Remapper;
import org.objectweb.asm.commons.RemappingMethodAdapter;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import codechicken.lib.vec.Vector3;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TileMultipart;
import codechicken.multipart.TileMultipartClient;
import codechicken.multipart.asm.MultipartMixinFactory;
import scala.collection.JavaConversions;
import scala.collection.immutable.Nil$;
/** Executes the shipped renderer method against real generated client tiles, replacing only its GL/pass services. */
class MultipartRendererFunctionalTest {
@BeforeEach
void resetRenderState() {
RenderServices.events.clear();
RenderServices.INSTANCE.useNormals = false;
RenderServices.dynamicCalls = 0;
RenderServices.position = null;
}
@Test
void nonemptyStaticTileReturnsWithoutTouchingRenderState() throws Exception {
TileMultipart tile = newClientTile();
RecordingPart part = new RecordingPart();
setParts(tile, part);
setField(tile, "hasDynamicParts", false);
render(tile);
assertTrue(RenderServices.events.isEmpty());
assertEquals(0, RenderServices.dynamicCalls);
}
@Test
void dynamicTileInitializesStateAndDispatchesWithTheSameCoordinatesFrameAndPass() throws Exception {
TileMultipart tile = newClientTile();
RecordingPart part = new RecordingPart();
setParts(tile, part);
setField(tile, "hasDynamicParts", true);
setField(tile, "codechicken$multipart$TileMultipartClient$$dynamicCache", new TMultiPart[] { part });
render(tile);
assertEquals(Arrays.asList("instance", "reset", "lightmap", "pass", "tile"), RenderServices.events);
assertEquals(1, RenderServices.dynamicCalls);
assertEquals(1.25, RenderServices.position.x);
assertEquals(-2.5, RenderServices.position.y);
assertEquals(3.75, RenderServices.position.z);
assertEquals(0.625F, RenderServices.frame);
assertEquals(1, RenderServices.pass);
assertTrue(RenderServices.INSTANCE.useNormals);
}
@Test
void emptyTileShortCircuitsEvenWithADynamicFlagAndCache() throws Exception {
TileMultipart tile = newClientTile();
RecordingPart part = new RecordingPart();
setField(tile, "hasDynamicParts", true);
setField(tile, "codechicken$multipart$TileMultipartClient$$dynamicCache", new TMultiPart[] { part });
render(tile);
assertTrue(RenderServices.events.isEmpty());
assertEquals(0, RenderServices.dynamicCalls);
}
@Test
void rejectsTilesWithoutTheClientTraitBeforeTouchingRenderState() throws Exception {
assertThrows(ClassCastException.class, () -> render(new TileMultipart()));
assertTrue(RenderServices.events.isEmpty());
}
private static TileMultipart newClientTile() throws Exception {
assertTrue(
TileMultipartClient.class.isInterface(),
"Exercise the transformed runtime type, not the Java input");
BitSet traits = new BitSet();
traits.set(MultipartMixinFactory.getId(TileMultipartClient.class.getName().replace('.', '/')));
TileMultipart generated = (TileMultipart) MultipartMixinFactory.construct(traits, Nil$.MODULE$);
// Keep the real generated interface/flag getter. Drawing is recorded because Forge strips the actual
// TMultiPart.renderDynamic method on this dedicated server.
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
String parent = Type.getInternalName(generated.getClass());
writer.visit(V1_8, ACC_PUBLIC, "codechicken/multipart/test/RendererRecordingTile", null, parent, null);
MethodVisitor init = writer.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
init.visitCode();
init.visitVarInsn(ALOAD, 0);
init.visitMethodInsn(INVOKESPECIAL, parent, "<init>", "()V", false);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
init.visitEnd();
String descriptor = "(Lcodechicken/lib/vec/Vector3;FI)V";
MethodVisitor draw = writer.visitMethod(ACC_PUBLIC, "renderDynamic", descriptor, null, null);
draw.visitCode();
draw.visitVarInsn(ALOAD, 1);
draw.visitVarInsn(FLOAD, 2);
draw.visitVarInsn(ILOAD, 3);
draw.visitMethodInsn(INVOKESTATIC, Type.getInternalName(RenderServices.class), "draw", descriptor, false);
draw.visitInsn(RETURN);
draw.visitMaxs(0, 0);
draw.visitEnd();
writer.visitEnd();
return (TileMultipart) new BodyLoader().define(writer.toByteArray()).getConstructor().newInstance();
}
private static void setParts(TileMultipart tile, TMultiPart... parts) {
tile.partList_$eq(JavaConversions.asScalaBuffer(Arrays.asList(parts)).toList());
}
private static void setField(TileMultipart tile, String name, Object value) throws Exception {
Field field = tile.getClass().getSuperclass().getDeclaredField(name);
field.setAccessible(true);
field.set(tile, value);
}
private static void render(TileEntity tile) throws Exception {
Object renderer = RendererBody.TYPE.getConstructor().newInstance();
try {
RendererBody.METHOD.invoke(renderer, tile, 1.25, -2.5, 3.75, 0.625F);
} catch (InvocationTargetException failure) {
Throwable cause = failure.getCause();
if (cause instanceof Error) throw (Error) cause;
if (cause instanceof Exception) throw (Exception) cause;
throw new AssertionError(cause);
}
}
private static final class RendererBody {
static final Class<?> TYPE;
static final Method METHOD;
static {
try {
// Loading the client-only TESR class on a server is forbidden. Copy its actual method body without
// changing any tile casts, field accesses or invocation opcodes; only rendering services are replaced.
ClassNode source = new ClassNode();
try (InputStream input = MultipartRendererFunctionalTest.class
.getResourceAsStream("/codechicken/multipart/MultipartRenderer$.class")) {
assertNotNull(input);
new ClassReader(input).accept(source, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
}
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
String name = "codechicken/multipart/test/HeadlessMultipartRenderer";
writer.visit(V1_8, ACC_PUBLIC, name, null, "java/lang/Object", null);
MethodVisitor init = writer.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
init.visitCode();
init.visitVarInsn(ALOAD, 0);
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
init.visitEnd();
boolean found = false;
for (MethodNode method : source.methods) {
if (!method.name.equals("renderTileEntityAt")) continue;
assertFalse(found);
found = true;
MethodVisitor target = writer.visitMethod(ACC_PUBLIC, method.name, method.desc, null, null);
method.accept(new RemappingMethodAdapter(ACC_PUBLIC, method.desc, target, new Remapper() {
@Override
public String map(String internalName) {
if (internalName.equals("codechicken/lib/render/CCRenderState")
|| internalName.equals("net/minecraftforge/client/MinecraftForgeClient"))
return Type.getInternalName(RenderServices.class);
return internalName;
}
}));
}
assertTrue(found);
writer.visitEnd();
TYPE = new BodyLoader().define(writer.toByteArray());
METHOD = TYPE.getMethod(
"renderTileEntityAt",
TileEntity.class,
double.class,
double.class,
double.class,
float.class);
} catch (Exception failure) {
throw new ExceptionInInitializerError(failure);
}
}
}
private static final class BodyLoader extends ClassLoader {
BodyLoader() {
super(MultipartRendererFunctionalTest.class.getClassLoader());
}
Class<?> define(byte[] bytes) {
return defineClass(null, bytes, 0, bytes.length);
}
}
public static final class RenderServices {
static final RenderServices INSTANCE = new RenderServices();
static final List<String> events = new ArrayList<>();
public boolean useNormals;
static int dynamicCalls;
static Vector3 position;
static float frame;
static int pass;
public static void draw(Vector3 position, float frame, int pass) {
assertTrue(INSTANCE.useNormals);
events.add("tile");
dynamicCalls++;
RenderServices.position = position;
RenderServices.frame = frame;
RenderServices.pass = pass;
}
public static RenderServices instance() {
events.add("instance");
return INSTANCE;
}
public void resetInstance() {
events.add("reset");
useNormals = false;
}
public void pullLightmapInstance() {
events.add("lightmap");
}
public static int getRenderPass() {
events.add("pass");
return 1;
}
}
private static final class RecordingPart extends TMultiPart {
@Override
public String getType() {
return "renderer-regression";
}
}
}
@@ -0,0 +1,295 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Scanner;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.ChunkPosition;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraft.world.chunk.Chunk;
import org.junit.jupiter.api.Test;
import codechicken.multipart.MultipartHelper;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TileMultipart;
import codechicken.multipart.handler.MultipartSaveLoad;
import codechicken.multipart.handler.MultipartSaveLoad$;
import codechicken.multipart.minecraft.ButtonPart;
import codechicken.multipart.minecraft.TorchPart;
class MultipartSaveLoadFunctionalTest {
@Test
void referenceScalaConsumerStillLinksToTheCompanionState() throws Exception {
World original = MultipartSaveLoad.loadingWorld();
World world = world();
try {
Class<?> fixtureClass = new FixtureClassLoader(MultipartSaveLoad.class.getClassLoader())
.define(loadFixture());
Object fixture = fixtureClass.getDeclaredConstructor().newInstance();
fixtureClass.getMethod("loadingWorld_$eq", World.class).invoke(fixture, world);
assertSame(world, MultipartSaveLoad.loadingWorld());
assertSame(world, MultipartSaveLoad$.MODULE$.loadingWorld());
assertSame(world, fixtureClass.getMethod("loadingWorld").invoke(fixture));
assertSame(MultipartSaveLoad.converters(), MultipartSaveLoad$.MODULE$.converters());
} finally {
MultipartSaveLoad.loadingWorld_$eq(original);
}
}
@Test
void hooksTheDummyTileAndGeneratedTileNamesIntoVanillaMaps() {
MultipartSaveLoad.hookLoader();
NBTTagCompound saved = new NBTTagCompound();
saved.setString("id", "savedMultipart");
saved.setInteger("x", 7);
saved.setInteger("y", 8);
saved.setInteger("z", 9);
TileEntity dummy = TileEntity.createAndLoadEntity(saved);
assertNotNull(dummy);
assertEquals("codechicken.multipart.handler.MultipartSaveLoad$TileNBTContainer", dummy.getClass().getName());
assertSame(saved, tag(dummy));
assertEquals(7, dummy.xCoord);
assertEquals(8, dummy.yCoord);
assertEquals(9, dummy.zCoord);
MultipartSaveLoad.registerTileClass(RegisteredTile.class);
assertEquals("savedMultipart", MultipartSaveLoad.getClassToNameMap().get(RegisteredTile.class));
NBTTagCompound registered = new NBTTagCompound();
new RegisteredTile().writeToNBT(registered);
assertEquals("savedMultipart", registered.getString("id"));
}
@Test
void leavesUnclaimedTilesRemovesEmptyConversionsAndUsesTheFirstMatch() {
World world = world();
Chunk chunk = new Chunk(world, 40, 40);
UnclaimedTile unclaimed = tile(new UnclaimedTile(), world);
ConvertedTile converted = tile(new ConvertedTile(), world);
converted.xCoord = 642;
converted.yCoord = 64;
converted.zCoord = 642;
DeletedTile deleted = tile(new DeletedTile(), world);
ChunkPosition unclaimedPosition = put(chunk, 1, unclaimed);
ChunkPosition convertedPosition = put(chunk, 2, converted);
ChunkPosition deletedPosition = put(chunk, 3, deleted);
RecordingConverter first = new RecordingConverter();
RejectingSecondConverter second = new RejectingSecondConverter();
MultipartHelper.registerTileConverter(first);
MultipartHelper.registerTileConverter(second);
MultipartHelper.registerTileConverter(new DeletingConverter());
MultipartSaveLoad.loadTiles(chunk);
assertSame(world, MultipartSaveLoad.loadingWorld());
assertSame(unclaimed, chunk.chunkTileEntityMap.get(unclaimedPosition));
assertFalse(chunk.chunkTileEntityMap.containsKey(deletedPosition));
TileMultipart replacement = assertInstanceOf(
TileMultipart.class,
chunk.chunkTileEntityMap.get(convertedPosition));
assertSame(world, replacement.getWorldObj());
assertEquals(converted.xCoord, replacement.xCoord);
assertEquals(converted.yCoord, replacement.yCoord);
assertEquals(converted.zCoord, replacement.zCoord);
NBTTagCompound saved = new NBTTagCompound();
replacement.writeToNBT(saved);
assertEquals(converted.xCoord, saved.getInteger("x"));
assertEquals(converted.yCoord, saved.getInteger("y"));
assertEquals(converted.zCoord, saved.getInteger("z"));
assertEquals(1, replacement.jPartList().size());
assertSame(first.part, replacement.jPartList().get(0));
assertEquals(1, first.calls);
assertEquals(0, second.calls);
}
@Test
void rebuildsSavedDummyTilesAndLeavesForeignDummiesUntouched() {
World world = world();
Chunk chunk = new Chunk(world, 41, 41);
TileMultipart savedTile = MultipartHelper
.createTileFromParts(Arrays.asList(new TorchPart(5), new ButtonPart(1)));
NBTTagCompound savedTag = new NBTTagCompound();
savedTile.writeToNBT(savedTag);
TileEntity savedDummy = dummy(savedTag, world);
ChunkPosition savedPosition = put(chunk, 1, savedDummy);
NBTTagCompound foreignTag = new NBTTagCompound();
foreignTag.setString("id", "foreign");
TileEntity foreignDummy = dummy(foreignTag, world);
ChunkPosition foreignPosition = put(chunk, 2, foreignDummy);
MultipartSaveLoad.loadTiles(chunk);
TileMultipart rebuilt = assertInstanceOf(TileMultipart.class, chunk.chunkTileEntityMap.get(savedPosition));
assertSame(world, rebuilt.getWorldObj());
assertEquals(2, rebuilt.jPartList().size());
assertEquals("mc_torch", rebuilt.jPartList().get(0).getType());
assertEquals("mc_button", rebuilt.jPartList().get(1).getType());
assertSame(foreignDummy, chunk.chunkTileEntityMap.get(foreignPosition));
}
@Test
void rebuildsTilesFromAStandaloneCubeMapWithTheEventWorld() {
World world = world();
TileMultipart savedTile = MultipartHelper.createTileFromParts(Arrays.asList(new TorchPart(5)));
savedTile.xCoord = 5;
savedTile.yCoord = 70;
savedTile.zCoord = 6;
NBTTagCompound savedTag = new NBTTagCompound();
savedTile.writeToNBT(savedTag);
ChunkPosition position = new ChunkPosition(5, 70, 6);
Map<ChunkPosition, TileEntity> tiles = new HashMap<>();
tiles.put(position, dummy(savedTag, null));
MultipartSaveLoad.loadTiles(world, tiles);
TileMultipart rebuilt = assertInstanceOf(TileMultipart.class, tiles.get(position));
assertSame(world, MultipartSaveLoad.loadingWorld());
assertSame(world, rebuilt.getWorldObj());
assertEquals(5, rebuilt.xCoord);
assertEquals(70, rebuilt.yCoord);
assertEquals(6, rebuilt.zCoord);
assertEquals("mc_torch", rebuilt.jPartList().get(0).getType());
}
private static TileEntity dummy(NBTTagCompound tag, World world) {
try {
TileEntity dummy = (TileEntity) Class
.forName("codechicken.multipart.handler.MultipartSaveLoad$TileNBTContainer")
.getDeclaredConstructor().newInstance();
dummy.readFromNBT(tag);
dummy.setWorldObj(world);
return dummy;
} catch (ReflectiveOperationException e) {
throw new AssertionError(e);
}
}
private static Object tag(TileEntity tile) {
try {
return tile.getClass().getMethod("tag").invoke(tile);
} catch (ReflectiveOperationException e) {
throw new AssertionError(e);
}
}
private static <T extends TileEntity> T tile(T tile, World world) {
tile.setWorldObj(world);
return tile;
}
private static ChunkPosition put(Chunk chunk, int offset, TileEntity tile) {
ChunkPosition position = new ChunkPosition(chunk.xPosition * 16 + offset, 64, chunk.zPosition * 16 + offset);
chunk.chunkTileEntityMap.put(position, tile);
return position;
}
private static WorldServer world() {
WorldServer world = MinecraftServer.getServer().worldServers[0];
assertNotNull(world);
assertFalse(world.isRemote);
return world;
}
private static byte[] loadFixture() {
InputStream input = Objects.requireNonNull(
MultipartSaveLoadFunctionalTest.class
.getResourceAsStream("/compat/ReferenceScalaMultipartSaveLoadConsumer.class.b64"));
try (Scanner scanner = new Scanner(input, StandardCharsets.US_ASCII.name()).useDelimiter("\\A")) {
return Base64.getMimeDecoder().decode(scanner.next());
}
}
private static final class FixtureClassLoader extends ClassLoader {
private FixtureClassLoader(ClassLoader parent) {
super(parent);
}
private Class<?> define(byte[] bytecode) {
return defineClass(null, bytecode, 0, bytecode.length);
}
}
private static class RegisteredTile extends TileEntity {
}
private static final class UnclaimedTile extends TileEntity {
}
private static final class ConvertedTile extends TileEntity {
}
private static final class DeletedTile extends TileEntity {
}
private static final class RecordingConverter extends MultipartHelper.IPartTileConverter<ConvertedTile> {
private final TMultiPart part = new TorchPart(3);
private int calls;
private RecordingConverter() {
super(ConvertedTile.class);
}
@Override
public TMultiPart convertOne(ConvertedTile tile) {
calls++;
return part;
}
}
private static final class RejectingSecondConverter extends MultipartHelper.IPartTileConverter<ConvertedTile> {
private int calls;
private RejectingSecondConverter() {
super(ConvertedTile.class);
}
@Override
public TMultiPart convertOne(ConvertedTile tile) {
calls++;
return new ButtonPart(1);
}
}
private static final class DeletingConverter extends MultipartHelper.IPartTileConverter<DeletedTile> {
private DeletingConverter() {
super(DeletedTile.class);
}
@Override
public Iterable<TMultiPart> convertMulti(DeletedTile tile) {
return Collections.emptyList();
}
@Override
public TMultiPart convertOne(DeletedTile tile) {
throw new AssertionError("convertMulti supplies the deletion result");
}
}
}
@@ -0,0 +1,210 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.World;
import org.junit.jupiter.api.Test;
import codechicken.lib.data.MCDataInput;
import codechicken.lib.data.MCDataOutput;
import codechicken.multipart.IScheduledPacketPart;
import codechicken.multipart.MultipartHelper;
import codechicken.multipart.PacketScheduler;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TileMultipart;
/**
* schedulePacket needs a part bound to a tile in a non-remote world, and sendScheduled needs a real write stream, so
* none of this runs headless. Tests execute inside the server-started event, so no tick can interleave and flush the
* map between a schedule and a send.
*/
class PacketSchedulerFunctionalTest {
@Test
void repeatedSchedulesAccumulateIntoOneMask() {
RecordingPart part = boundPart(1);
PacketScheduler.schedulePacket(part, 0x1L);
PacketScheduler.schedulePacket(part, 0x2L);
PacketScheduler.schedulePacket(part, 0x2L);
sendScheduled();
assertEquals(Collections.singletonList(0x3L), part.written, "masks are OR-ed, and the part is written once");
}
@Test
void sendingClearsTheScheduleSoTheNextTickWritesNothing() {
RecordingPart part = boundPart(1);
PacketScheduler.schedulePacket(part, 0x5L);
sendScheduled();
sendScheduled();
assertEquals(Collections.singletonList(0x5L), part.written);
}
@Test
void callbacksCanScheduleAnotherPartDuringTheFlush() {
RecordingPart first = boundPart(1, 0);
RecordingPart second = boundPart(1, 1);
// These hashes place the new entry in a bucket still ahead of Scala's original traversal.
RecordingPart added = boundPart(1, 3);
first.onWrite = () -> PacketScheduler.schedulePacket(added, 0x4L);
second.onWrite = first.onWrite;
try {
PacketScheduler.schedulePacket(first, 0x1L);
PacketScheduler.schedulePacket(second, 0x2L);
sendScheduled();
assertEquals(Collections.singletonList(0x1L), first.written);
assertEquals(Collections.singletonList(0x2L), second.written);
assertEquals(Collections.singletonList(0x4L), added.written);
sendScheduled();
assertEquals(1, first.written.size());
assertEquals(1, second.written.size());
assertEquals(1, added.written.size());
} finally {
first.tile_$eq(null);
second.tile_$eq(null);
added.tile_$eq(null);
sendScheduled();
}
}
@Test
void callbacksMergeMasksIntoEntriesThatHaveNotBeenWrittenYet() {
RecordingPart first = boundPart(1, 0);
RecordingPart second = boundPart(1, 1);
first.onWrite = () -> PacketScheduler.schedulePacket(second, 0x4L);
second.onWrite = () -> PacketScheduler.schedulePacket(first, 0x8L);
try {
PacketScheduler.schedulePacket(first, 0x1L);
PacketScheduler.schedulePacket(second, 0x2L);
sendScheduled();
assertEquals(1, first.written.size());
assertEquals(1, second.written.size());
assertTrue(
first.written.get(0) == 0x9L && second.written.get(0) == 0x2L
|| first.written.get(0) == 0x1L && second.written.get(0) == 0x6L,
"Whichever part is visited second must receive the mask added by the first callback");
sendScheduled();
assertEquals(1, first.written.size());
assertEquals(1, second.written.size());
} finally {
first.tile_$eq(null);
second.tile_$eq(null);
sendScheduled();
}
}
@Test
void aPartThatLostItsTileIsSkippedButStillCleared() {
RecordingPart part = boundPart(1);
PacketScheduler.schedulePacket(part, 0x7L);
part.tile_$eq(null);
sendScheduled();
assertTrue(part.written.isEmpty(), "a part with no tile must be skipped");
}
@Test
void everyDocumentedMaskWidthIsAccepted() {
for (int width : new int[] { 1, 2, 4, 8 }) {
RecordingPart part = boundPart(width);
PacketScheduler.schedulePacket(part, 0x1L);
sendScheduled();
assertEquals(Collections.singletonList(0x1L), part.written, "maskWidth " + width + " must be accepted");
}
}
/** The reference matches on 1, 2, 4 and 8 with no fallback, so anything else fails rather than writing nothing. */
@Test
void anUndocumentedMaskWidthIsRejected() {
RecordingPart part = boundPart(3);
PacketScheduler.schedulePacket(part, 0x1L);
assertThrows(RuntimeException.class, PacketSchedulerFunctionalTest::sendScheduled);
// Leave no scheduled entry behind for the tests that follow.
part.tile_$eq(null);
try {
sendScheduled();
} catch (RuntimeException ignored) {
// already drained
}
}
// The only place sendScheduled's owner is named.
private static void sendScheduled() {
PacketScheduler.sendScheduled();
}
private static RecordingPart boundPart(int maskWidth) {
return boundPart(maskWidth, 0);
}
private static RecordingPart boundPart(int maskWidth, int hash) {
RecordingPart part = new RecordingPart(maskWidth, hash);
TileMultipart tile = MultipartHelper.createTileFromParts(Collections.<TMultiPart>singletonList(part));
assertNotNull(tile);
World world = MinecraftServer.getServer().worldServers[0];
assertNotNull(world);
tile.setWorldObj(world);
tile.xCoord = 1100;
tile.yCoord = 70;
tile.zCoord = 1100;
return part;
}
private static final class RecordingPart extends TMultiPart implements IScheduledPacketPart {
private final int maskWidth;
private final int hash;
final List<Long> written = new ArrayList<>();
Runnable onWrite;
RecordingPart(int maskWidth, int hash) {
this.maskWidth = maskWidth;
this.hash = hash;
}
@Override
public int hashCode() {
return hash;
}
@Override
public String getType() {
return "test:scheduled";
}
@Override
public int maskWidth() {
return maskWidth;
}
@Override
public void writeScheduled(long mask, MCDataOutput packet) {
written.add(mask);
if (onWrite != null) {
onWrite.run();
}
}
@Override
public void readScheduled(long mask, MCDataInput packet) {}
}
}
Loaded 100 of 618 files, more files were not shown because too many files have changed in this diff. Show more