Compare commits

...
81 Commits
Author SHA1 Message Date
Ressed 9eb69cdc13 Fix MissingMicroMaterial microblock crafted instead of Minecraft:stone (#61) 2026-10-03 20:14:54 -05:00
RecursivePineappleandMartin Robertz 7808254465 Fix TE interceptor for CC (#49)
Co-authored-by: Martin Robertz <[email protected]>
2026-09-15 14:29:59 -04:00
Pxx500 71340a23ef avoid callbacks to parts transferred to another tile (#58) 2026-09-12 20:06:49 +02:00
Ryan Nasers 2d050bdd08 Additional ISBRH compat + JSONModel Compat from GTNHLib (#54) 2026-09-06 23:45:06 +02:00
Ryan Nasers f10595d062 Isbrh interface fmp (#53) 2026-08-13 12:14:59 +02:00
Jason Mitchell 7221176efd Maybe more thread safe renderpass (#50) 2026-07-22 15:30:42 -07:00
DarkShadow44andRecursivePineapple aa7d02cfb0 Don't use rock material (#45)
Co-authored-by: RecursivePineapple <[email protected]>
2026-07-05 00:05:47 +00:00
FourIsTheNumber d2ce5b7362 Add postea transformer for microblock items (#48) 2026-07-04 20:02:17 -04:00
Caedis 09e2b847fc fix(microblock): prevent microblocks becoming blood rune slabs (#47) 2026-06-21 09:20:32 +02:00
Dan faa052f70c fix npe on chunk unload when tile is null (#46) 2026-06-05 20:58:04 +02:00
Alexdoruandboubou19 15298cb677 [Memory-opti:fix leak] fix world client leak in renderer (#44)
Co-authored-by: boubou19 <[email protected]>
2026-04-30 11:18:51 +02:00
Alexdoru d3054211db [Memory-opti:fix leak] fix world client from keybind handler (#43) 2026-04-30 11:13:22 +02:00
Martin Robertz 732f64a1b4 update+gradle+deps+bs 2026-04-27 13:42:24 +02:00
UltraProdigy 2a5e2a150f Optimize Images & Workflow (#42) 2026-04-26 08:39:13 +02:00
Alexdoru 1a4edfbc89 fix world server leak (#41) 2026-04-14 14:48:23 +00:00
Worive 525fcc56ad Update buildscript to v2 (#40) 2026-03-08 19:23:42 +01:00
Woriveandgithub-actions[bot] a36120fc91 Add dynamic render option without relying on doesTick (#38)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-12-08 10:50:16 +01:00
Worive 238b041f12 Revert light value caching, applying better iteration to avoid null exceptions (#37) 2025-12-08 10:04:49 +01:00
Worive 0b0e99024d Optimize FMP Rendering and memory leaks (#35) 2025-12-06 12:07:08 +01:00
Martin Robertz a1db9a100e update 2025-10-24 23:00:37 +02:00
DarkShadow44 3c42abd7ac Allow y coordinates bigger 255 (#32) 2025-10-24 05:34:05 +00:00
Alexdoru f3a0ab0568 Delete DepLoader and declare depency properly (#31) 2025-08-01 00:42:50 +02:00
Caedis a0af5e19cf Force render return type to Unit (#30) 2025-07-02 01:16:53 +00:00
Alexdoru 3f27188181 Fix crash introduced by memory leak fix (#29) 2025-06-07 11:55:43 +02:00
Martin Robertz 4fc6b9cff2 sa 2025-06-05 21:45:59 +02:00
Maya ef67761bc3 update 2025-06-03 12:52:42 -06:00
Alexdoru d50ec43d76 Fix WorldClient leak (#28) 2025-06-03 12:52:09 -06:00
David Lindström 05eb683a33 Forward material to shader (#27) 2025-05-27 23:22:56 +02:00
Dream Master 11b6142320 update 2025-01-15 12:39:45 +01:00
Glease de264540d2 fix rare client world leak (#26) 2025-01-13 00:12:45 -06:00
Martin Robertz bc3542efd2 fix Instance() 2024-12-31 15:41:21 +01:00
Martin Robertz ad7a1d3cea Update dependencies.gradle 2024-12-31 15:06:58 +01:00
Martin Robertz 1bd4ef4a0f update 2024-12-31 14:24:36 +01:00
glowredman 439243b00a Add Localization (#25) 2024-12-30 18:18:34 -06:00
Martin Robertz 38a2bf629f update 2024-05-26 12:44:42 +02:00
Jason Mitchell 2abb775696 Thread saftey (#24)
* Update BS

* Thread Safety
2024-05-26 12:41:45 +02:00
Martin Robertz b60993f39b update 2024-02-13 10:17:19 +01:00
glowredman 76a1df6eff Add version to @Mod annotations (#23) 2024-02-12 23:35:09 +01:00
Raven Szewczyk 25b74b4bbc [ci skip] upgraded build system 2024-02-04 19:58:36 +00:00
bombcarandMartin Robertz f4a9610e22 Re-add dependencies.info corrected, update BS etc (#22)
* read corrected dependencies.info

* update bs, dependencies, and settings.gradle

---------

Co-authored-by: Martin Robertz <[email protected]>
2024-01-10 00:26:17 +01:00
Martin Robertz 3a01a5bd21 update bs+deps 2024-01-08 23:48:23 +01:00
Raven Szewczyk 83feeeec8e [ci skip] upgraded build system 2024-01-08 21:25:48 +00:00
bombcar 901dfcb5a0 Merge pull request #21 from GTNewHorizons/chicken
update to support 1.2.0 CCL - needs work to be more performant
2024-01-03 05:38:30 -06:00
bombcar 794c3ca030 fix the rest 2024-01-02 13:07:44 -06:00
bombcar ee37e779fd partial maintain state 2024-01-02 13:02:02 -06:00
bombcar 5039fb8984 update to support 1.2.0 CCL - needs work to be more performant 2024-01-02 11:38:11 -06:00
Martin Robertz cb276d92f5 update bs 2024-01-01 20:21:30 +01:00
Roadhog360andMartin Robertz d336cfbb67 Fix ButtonPart.java crashes, tweaks to allow mods to hook it (#20)
* Fix ButtonPart.java crashes, tweaks to allow mods to hook it
`ButtonPart`:
- Rewrite `getBounds()` to use a list generated from the button hitbox itself, instead of being a hardcoded list. Then mods like Et Futurum Requiem which change buttons only have to mix to `metaSideMap` and `sideMetaMap`
  - This adds an access transformer to get the button hitbox states, which are ordinarily private.
- Change `placement` to check if the corresponding side's value in `sideMetaMap` is `-1` instead of a hardcoded side check, so top/bottom is still unplaceable unless mods add it.
`McSidedMetaPart.java`:
- Fix crash from out of bounds side values from meta (notably in this commit, `-1` from buttons) by making any value below 0 or above 5 return false.

* update bs+sa+gradle+deps

* backdate ccl mod

* derp

---------

Co-authored-by: Martin Robertz <[email protected]>
2023-12-31 16:40:51 +01:00
Ryan Nasers ce032ee9a8 Potential Fix to some FMP stuff relating to Redstone parts not connecting to bottoms of machines. (#18)
* BS Update and spotlessApply

* Forgot this bit

* Changing a line that I'm not actually sure if it will break things
2023-11-25 15:33:31 +01:00
Martin Robertz 819d28b993 update bs+deps 2023-11-08 08:13:28 +01:00
rjnasers f2dc70a3c9 Forgot this bit 2023-11-06 17:23:20 +01:00
rjnasers 75958e3892 BS Update and spotlessApply 2023-11-06 17:23:20 +01:00
miozune 2f6bd45e4f Update build (#16)
* Update build

* spotlessApply
2023-06-27 17:23:32 +09:00
chochem 97b7cf0847 Merge pull request #15 from chochem/master
update dep
2023-04-27 16:39:29 +01:00
chochem eb8256c355 dep 2023-04-27 16:31:44 +01:00
Martin Robertz 8bf873dd71 Merge pull request #14 from GTNewHorizons/keybind
keybinds
2023-02-05 21:03:52 +01:00
Alexdoru 909643e9a2 spell block correct 2023-02-05 20:12:29 +01:00
Alexdoru aa631173a2 unbind key by default and move key to its own category "Forge Multipart" 2023-02-05 20:10:56 +01:00
Alexdoru e3bf9e3b79 missing localisation for keybind name 2023-02-05 20:09:44 +01:00
Raven Szewczyk 52d885280a [ci skip] upgraded build system 2023-01-31 09:52:53 +00:00
Jason Mitchell eeab28e07b [ci skip] Add git-blame-ignore-revs for spotlessApply 2023-01-29 10:24:12 -08:00
Jason Mitchell 6b18eca613 [ci skip] spotlessApply with the new settings 2023-01-29 10:24:12 -08:00
Jason Mitchell f02b6bae19 [ci skip] Update buildscript to RetroFuturaGradle 2023-01-29 10:23:31 -08:00
Martin Robertz 00327aad3b Merge pull request #13 from GTNewHorizons/fix-asm-bad-type
Fix wrong asm types being used for TypeInsnNodes
2023-01-19 18:31:19 +01:00
Raven Szewczyk 1ba2172e8a Fix wrong asm types being used for TypeInsnNodes 2023-01-19 17:12:21 +00:00
Raven Szewczyk ed155c644c Apply spotless 2023-01-19 15:34:07 +00:00
Raven Szewczyk 845b5f68c7 Update buildscript 2023-01-19 15:33:54 +00:00
boubou19 0106b4e5bc Merge pull request #12 from GTNewHorizons/log-spam
Remove logging of all microblock materials: -400kiB of logs on GTNH
2022-09-26 20:13:41 +02:00
Raven Szewczyk 12bc43c8d4 Remove logging of all microblock materials: -400kiB of logs on GTNH 2022-09-26 19:07:40 +01:00
Martin Robertz b0097f4c2e Merge pull request #11 from GTNewHorizons/update-ccl
Update codechickenlib
2022-09-19 13:35:48 +02:00
Raven Szewczyk 3e877b618e Update codechickenlib 2022-09-18 22:04:11 +01:00
Jason Mitchell cce6c61061 [ci skip] Migrate github actions to GTNH-Actions-Workflows 2022-07-16 10:48:18 -07:00
Martin Robertz 7c09417b1c Merge pull request #10 from GTNewHorizons/mop
Ducttape crash
2022-05-25 17:36:59 +02:00
miozune 19a6540aff Ducttape crash 2022-05-25 16:55:12 +09:00
Jason Mitchell 8ee4202610 update to explicit dependencies 2022-01-17 22:09:29 -08:00
Jason Mitchell 4509df8f1b maven publish buildscript update 2022-01-17 22:09:17 -08:00
Martin Robertz e3a9ba324b Merge pull request #9 from boubou19/master
disabled recipe addition when NHCore is present
2022-01-09 14:30:06 +01:00
boubou_19 2e762a04c1 disabled recipe addition when NHCore is present 2022-01-08 14:59:58 +01:00
Martin Robertz 6188bc655d Merge pull request #8 from GTNewHorizons/dependencies
Update dependencies
2021-12-23 17:31:58 +01:00
bombcar 496eb2b3ea update buildscript 2021-12-22 13:48:00 -06:00
bombcar 24aa5f818e fix dependencies to use our github 2021-12-22 13:47:38 -06:00
131 changed files with 9783 additions and 8819 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
# Ignore spotlessApply reformat
6b18eca613ddece54a44d27ac40fc7b62826f3a7
+44
View File
@@ -0,0 +1,44 @@
* text eol=lf
*.[jJ][aA][rR] binary
*.[pP][nN][gG] binary
*.[jJ][pP][gG] binary
*.[jJ][pP][eE][gG] binary
*.[gG][iI][fF] binary
*.[tT][iI][fF] binary
*.[tT][iI][fF][fF] binary
*.[iI][cC][oO] binary
*.[sS][vV][gG] text
*.[eE][pP][sS] binary
*.[xX][cC][fF] binary
*.[kK][aA][rR] binary
*.[mM]4[aA] binary
*.[mM][iI][dD] binary
*.[mM][iI][dD][iI] binary
*.[mM][pP]3 binary
*.[oO][gG][gG] binary
*.[rR][aA] binary
*.7[zZ] binary
*.[gG][zZ] binary
*.[tT][aA][rR] binary
*.[tT][gG][zZ] binary
*.[zZ][iI][pP] binary
*.[tT][cC][nN] binary
*.[sS][oO] binary
*.[dD][lL][lL] binary
*.[dD][yY][lL][iI][bB] binary
*.[pP][sS][dD] binary
*.[tT][tT][fF] binary
*.[oO][tT][fF] binary
*.[pP][aA][tT][cC][hH] -text
*.[bB][aA][tT] text eol=crlf
*.[cC][mM][dD] text eol=crlf
*.[pP][sS]1 text eol=crlf
*[aA][uU][tT][oO][gG][eE][nN][eE][rR][aA][tT][eE][dD]* binary
-9
View File
@@ -1,9 +0,0 @@
directory="run/crash-reports"
if [ -d $directory ]; then
echo "Crash reports detected:"
cat $directory/*
exit 1
else
echo "No crash reports detected"
exit 0
fi
+2 -34
View File
@@ -1,5 +1,3 @@
# This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle
name: Build and test name: Build and test
@@ -11,35 +9,5 @@ on:
jobs: jobs:
build-and-test: build-and-test:
runs-on: ubuntu-latest uses: GTNewHorizons/GTNH-Actions-Workflows/.github/workflows/build-and-test.yml@master
steps: secrets: inherit
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Set up JDK 8
uses: actions/setup-java@v2
with:
java-version: '8'
distribution: 'adopt'
cache: gradle
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Setup the workspace
run: ./gradlew setupCIWorkspace
- name: Build the mod
run: ./gradlew build
- name: Run server for 1 minute
run: |
mkdir run
echo "eula=true" > run/eula.txt
timeout 10 ./gradlew runServer || true
- name: Test no crashes happend
run: |
chmod +x .github/scripts/test-no-crash-reports.sh
.github/scripts/test-no-crash-reports.sh
+17
View File
@@ -0,0 +1,17 @@
name: Optimize images
on:
pull_request:
branches: [ master, main, release/** ]
paths:
- "**/*.png"
push:
branches: [ master, main, release/** ]
paths:
- "**/*.png"
jobs:
optimize-images:
uses: GTNewHorizons/GTNH-Actions-Workflows/.github/workflows/optimize-images.yml@master
secrets: inherit
+7 -38
View File
@@ -1,45 +1,14 @@
# This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle
name: Release tagged build name: Release tagged build
on: on:
push: push:
tags: tags: [ '*' ]
- '*'
permissions:
contents: write
jobs: jobs:
build: release-tags:
runs-on: ubuntu-latest uses: GTNewHorizons/GTNH-Actions-Workflows/.github/workflows/release-tags.yml@master
steps: secrets: inherit
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Set release version
run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV
- name: Set up JDK 8
uses: actions/setup-java@v2
with:
java-version: '8'
distribution: 'adopt'
cache: gradle
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Setup the workspace
run: ./gradlew setupCIWorkspace
- name: Build the mod
run: ./gradlew build
- name: Release under current tag
uses: "marvinpinto/action-automatic-releases@latest"
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
automatic_release_tag: "${{ env.RELEASE_VERSION }}"
prerelease: false
title: "${{ env.RELEASE_VERSION }}"
files: build/libs/*.jar
+2 -1
View File
@@ -25,5 +25,6 @@ whitelist.json
*.iml *.iml
*.ipr *.ipr
*.iws *.iws
src/main/resources/mixins.*.json src/main/resources/mixins.*.refmap.json
*.bat *.bat
layout.json
+3
View File
@@ -0,0 +1,3 @@
# Any Github changes require admin approval
/.github/** @GTNewHorizons/admin
+2 -514
View File
@@ -1,517 +1,5 @@
//version: ffe7b130f98fdfa1ac7c6ba4bd34722a55ab28d4 //version: 1707058017
/*
DO NOT CHANGE THIS FILE!
Also, you may replace this file at any time if there is an update available.
Please check https://github.com/SinTh0r4s/ExampleMod1.7.10/blob/main/build.gradle for updates.
*/
import com.github.jengelman.gradle.plugins.shadow.tasks.ConfigureShadowRelocation
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import java.util.concurrent.TimeUnit
buildscript {
repositories {
maven {
name = "forge"
url = "https://maven.minecraftforge.net"
}
maven {
name = "sonatype"
url = "https://oss.sonatype.org/content/repositories/snapshots/"
}
maven {
name = "Scala CI dependencies"
url = "https://repo1.maven.org/maven2/"
}
maven {
name = "jitpack"
url = "https://jitpack.io"
}
}
dependencies {
classpath 'com.github.GTNewHorizons:ForgeGradle:1.2.4'
}
}
plugins { plugins {
id 'idea' id 'com.gtnewhorizons.gtnhconvention'
id 'scala'
id("org.ajoberstar.grgit") version("3.1.1")
id("com.github.johnrengelman.shadow") version("4.0.4")
id("com.palantir.git-version") version("0.12.3")
}
apply plugin: 'forge'
def projectJavaVersion = JavaLanguageVersion.of(8)
java {
toolchain {
languageVersion.set(projectJavaVersion)
}
}
idea {
module {
inheritOutputDirs = true
downloadJavadoc = true
downloadSources = true
}
}
if(JavaVersion.current() != JavaVersion.VERSION_1_8) {
throw new GradleException("This project requires Java 8, but it's running on " + JavaVersion.current())
}
checkPropertyExists("modName")
checkPropertyExists("modId")
checkPropertyExists("modGroup")
checkPropertyExists("autoUpdateBuildScript")
checkPropertyExists("minecraftVersion")
checkPropertyExists("forgeVersion")
checkPropertyExists("replaceGradleTokenInFile")
checkPropertyExists("gradleTokenModId")
checkPropertyExists("gradleTokenModName")
checkPropertyExists("gradleTokenVersion")
checkPropertyExists("gradleTokenGroupName")
checkPropertyExists("apiPackage")
checkPropertyExists("accessTransformersFile")
checkPropertyExists("usesMixins")
checkPropertyExists("mixinPlugin")
checkPropertyExists("mixinsPackage")
checkPropertyExists("coreModClass")
checkPropertyExists("containsMixinsAndOrCoreModOnly")
checkPropertyExists("usesShadowedDependencies")
checkPropertyExists("developmentEnvironmentUserName")
def checkPropertyExists(String propertyName) {
if (project.hasProperty(propertyName) == false) {
throw new GradleException("This project requires a property \"" + propertyName + "\"! Please add it your \"gradle.properties\". You can find all properties and their description here: https://github.com/SinTh0r4s/ExampleMod1.7.10/blob/main/gradle.properties")
}
}
String javaSourceDir = "src/main/java/"
String scalaSourceDir = "src/main/scala/"
String targetPackageJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/")
String targetPackageScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/")
if((new File(targetPackageJava).exists() || new File(targetPackageScala).exists()) == false) {
throw new GradleException("Could not resolve \"modGroup\"! Could not find " + targetPackageJava + " or " + targetPackageScala)
}
if(apiPackage) {
targetPackageJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/")
targetPackageScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/")
if((new File(targetPackageJava).exists() || new File(targetPackageScala).exists()) == false) {
throw new GradleException("Could not resolve \"apiPackage\"! Could not find " + targetPackageJava + " or " + targetPackageScala)
}
}
if(accessTransformersFile) {
String targetFile = "src/main/resources/META-INF/" + accessTransformersFile
if(new File(targetFile).exists() == false) {
throw new GradleException("Could not resolve \"accessTransformersFile\"! Could not find " + targetFile)
}
}
if(usesMixins.toBoolean()) {
if(mixinsPackage.isEmpty() || mixinPlugin.isEmpty()) {
throw new GradleException("\"mixinPlugin\" requires \"mixinsPackage\" and \"mixinPlugin\" to be set!")
}
targetPackageJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinsPackage.toString().replaceAll("\\.", "/")
targetPackageScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinsPackage.toString().replaceAll("\\.", "/")
if((new File(targetPackageJava).exists() || new File(targetPackageScala).exists()) == false) {
throw new GradleException("Could not resolve \"mixinsPackage\"! Could not find " + targetPackageJava + " or " + targetPackageScala)
}
String targetFileJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".java"
String targetFileScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".scala"
String targetFileScalaJava = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".java"
if((new File(targetFileJava).exists() || new File(targetFileScala).exists() || new File(targetFileScalaJava).exists()) == false) {
throw new GradleException("Could not resolve \"mixinPlugin\"! Could not find " + targetFileJava + " or " + targetFileScala + " or " + targetFileScalaJava)
}
}
if(coreModClass) {
String targetFileJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".java"
String targetFileScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".scala"
String targetFileScalaJava = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".java"
if((new File(targetFileJava).exists() || new File(targetFileScala).exists() || new File(targetFileScalaJava).exists()) == false) {
throw new GradleException("Could not resolve \"coreModClass\"! Could not find " + targetFileJava + " or " + targetFileScala + " or " + targetFileScalaJava)
}
}
configurations.all {
resolutionStrategy.cacheChangingModulesFor(0, TimeUnit.SECONDS)
// Make sure GregTech build won't time out
System.setProperty("org.gradle.internal.http.connectionTimeout", 120000 as String)
System.setProperty("org.gradle.internal.http.socketTimeout", 120000 as String)
}
// Fix Jenkins' Git: chmod a file should not be detected as a change and append a '.dirty' to the version
'git config core.fileMode false'.execute()
// Pulls version from git tag
try {
version = minecraftVersion + "-" + gitVersion()
}
catch (Exception e) {
throw new IllegalStateException("This mod must be version controlled by Git AND the repository must provide at least one tag!");
}
group = modGroup
archivesBaseName = modId
minecraft {
version = minecraftVersion + "-" + forgeVersion + "-" + minecraftVersion
runDir = "run"
if (replaceGradleTokenInFile) {
replaceIn replaceGradleTokenInFile
if(gradleTokenModId) {
replace gradleTokenModId, modId
}
if(gradleTokenModName) {
replace gradleTokenModName, modName
}
if(gradleTokenVersion) {
replace gradleTokenVersion, versionDetails().lastTag
}
if(gradleTokenGroupName) {
replace gradleTokenGroupName, modGroup
}
}
}
if(file("addon.gradle").exists()) {
apply from: "addon.gradle"
}
apply from: 'repositories.gradle'
configurations {
implementation.extendsFrom(shadowImplementation)
}
repositories {
maven {
name = "Overmind forge repo mirror"
url = "https://gregtech.overminddl1.com/"
}
if(usesMixins.toBoolean()) {
maven {
name = "sponge"
url = "https://repo.spongepowered.org/repository/maven-public"
}
maven {
url = "https://jitpack.io"
}
}
}
dependencies {
if(usesMixins.toBoolean()) {
annotationProcessor("org.ow2.asm:asm-debug-all:5.0.3")
annotationProcessor("com.google.guava:guava:24.1.1-jre")
annotationProcessor("com.google.code.gson:gson:2.8.6")
annotationProcessor("org.spongepowered:mixin:0.8-SNAPSHOT")
// using 0.8 to workaround a issue in 0.7 which fails mixin application
compile("org.spongepowered:mixin:0.7.11-SNAPSHOT") {
// Mixin includes a lot of dependencies that are too up-to-date
exclude module: "launchwrapper"
exclude module: "guava"
exclude module: "gson"
exclude module: "commons-io"
exclude module: "log4j-core"
}
compile("com.github.GTNewHorizons:SpongeMixins:1.3.3:dev")
}
}
apply from: 'dependencies.gradle'
def mixingConfigRefMap = "mixins." + modId + ".refmap.json"
def refMap = "${tasks.compileJava.temporaryDir}" + File.separator + mixingConfigRefMap
def mixinSrg = "${tasks.reobf.temporaryDir}" + File.separator + "mixins.srg"
task generateAssets {
if(usesMixins.toBoolean()) {
new File(projectDir.toString() + "/src/main/resources/", "mixins." + modId + ".json").text = """{
"required": true,
"minVersion": "0.7.11",
"package": "${modGroup}.${mixinsPackage}",
"plugin": "${modGroup}.${mixinPlugin}",
"refmap": "${mixingConfigRefMap}",
"target": "@env(DEFAULT)",
"compatibilityLevel": "JAVA_8"
}
"""
}
}
task relocateShadowJar(type: ConfigureShadowRelocation) {
target = tasks.shadowJar
prefix = modGroup + ".shadow"
}
shadowJar {
manifest {
attributes(getManifestAttributes())
}
minimize() // This will only allow shading for actually used classes
configurations = [project.configurations.shadowImplementation]
dependsOn(relocateShadowJar)
}
jar {
manifest {
attributes(getManifestAttributes())
}
if(usesShadowedDependencies.toBoolean()) {
dependsOn(shadowJar)
enabled = false
}
}
reobf {
if(usesMixins.toBoolean()) {
addExtraSrgFile mixinSrg
}
}
afterEvaluate {
if(usesMixins.toBoolean()) {
tasks.compileJava {
options.compilerArgs += [
"-AreobfSrgFile=${tasks.reobf.srg}",
"-AoutSrgFile=${mixinSrg}",
"-AoutRefMapFile=${refMap}",
// Elan: from what I understand they are just some linter configs so you get some warning on how to properly code
"-XDenableSunApiLintControl",
"-XDignore.symbol.file"
]
}
}
}
runClient {
def arguments = []
if(usesMixins.toBoolean()) {
arguments += [
"--mods=../build/libs/$modId-${version}.jar",
"--tweakClass org.spongepowered.asm.launch.MixinTweaker"
]
}
if(developmentEnvironmentUserName) {
arguments += [
"--username",
developmentEnvironmentUserName
]
}
args(arguments)
}
runServer {
def arguments = []
if (usesMixins.toBoolean()) {
arguments += [
"--mods=../build/libs/$modId-${version}.jar",
"--tweakClass org.spongepowered.asm.launch.MixinTweaker"
]
}
args(arguments)
}
tasks.withType(JavaExec).configureEach {
javaLauncher.set(
javaToolchains.launcherFor {
languageVersion = projectJavaVersion
}
)
}
processResources
{
// this will ensure that this task is redone when the versions change.
inputs.property "version", project.version
inputs.property "mcversion", project.minecraft.version
// replace stuff in mcmod.info, nothing else
from(sourceSets.main.resources.srcDirs) {
include 'mcmod.info'
// replace version and mcversion
expand "minecraftVersion": project.minecraft.version,
"modVersion": versionDetails().lastTag,
"modId": modId,
"modName": modName
}
if(usesMixins.toBoolean()) {
from refMap
}
// copy everything else, thats not the mcmod.info
from(sourceSets.main.resources.srcDirs) {
exclude 'mcmod.info'
}
}
def getManifestAttributes() {
def manifestAttributes = [:]
if(containsMixinsAndOrCoreModOnly.toBoolean() == false && (usesMixins.toBoolean() || coreModClass)) {
manifestAttributes += ["FMLCorePluginContainsFMLMod": true]
}
if(accessTransformersFile) {
manifestAttributes += ["FMLAT" : accessTransformersFile.toString()]
}
if(coreModClass) {
manifestAttributes += ["FMLCorePlugin": modGroup + "." + coreModClass]
}
if(usesMixins.toBoolean()) {
manifestAttributes += [
"TweakClass" : "org.spongepowered.asm.launch.MixinTweaker",
"MixinConfigs" : "mixins." + modId + ".json",
"ForceLoadAsMod" : containsMixinsAndOrCoreModOnly.toBoolean() == false
]
}
return manifestAttributes
}
task sourcesJar(type: Jar) {
from (sourceSets.main.allJava)
from (file("$projectDir/LICENSE"))
getArchiveClassifier().set('sources')
}
task shadowDevJar(type: ShadowJar) {
from sourceSets.main.output
getArchiveClassifier().set("dev")
manifest {
attributes(getManifestAttributes())
}
minimize() // This will only allow shading for actually used classes
configurations = [project.configurations.shadowImplementation]
}
task relocateShadowDevJar(type: ConfigureShadowRelocation) {
target = tasks.shadowDevJar
prefix = modGroup + ".shadow"
}
task circularResolverJar(type: Jar) {
dependsOn(relocateShadowDevJar)
dependsOn(shadowDevJar)
enabled = false
}
task devJar(type: Jar) {
from sourceSets.main.output
getArchiveClassifier().set("dev")
manifest {
attributes(getManifestAttributes())
}
if(usesShadowedDependencies.toBoolean()) {
dependsOn(circularResolverJar)
enabled = false
}
}
task apiJar(type: Jar) {
from (sourceSets.main.allJava) {
include modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString() + '/**'
}
from (sourceSets.main.output) {
include modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString() + '/**'
}
from (sourceSets.main.resources.srcDirs) {
include("LICENSE")
}
getArchiveClassifier().set('api')
}
artifacts {
archives sourcesJar
archives devJar
if(apiPackage) {
archives apiJar
}
}
// Updating
task updateBuildScript {
doLast {
if (updateBuildScript()) return
print("Build script already up-to-date!")
}
}
if (isNewBuildScriptVersionAvailable()) {
if (autoUpdateBuildScript.toBoolean()) {
updateBuildScript()
} else {
println("Build script update available! Run 'gradle updateBuildScript'")
}
}
static URL availableBuildScriptUrl() {
new URL("https://raw.githubusercontent.com/SinTh0r4s/ExampleMod1.7.10/main/build.gradle")
}
static boolean updateBuildScript() {
if (isNewBuildScriptVersionAvailable()) {
def buildscriptFile = new File("build.gradle")
availableBuildScriptUrl().withInputStream { i -> buildscriptFile.withOutputStream { it << i } }
print("Build script updated. Please REIMPORT the project or RESTART your IDE!")
return true
}
return false
}
static boolean isNewBuildScriptVersionAvailable() {
Map parameters = ["connectTimeout": 2000, "readTimeout": 2000]
String currentBuildScript = new File("build.gradle").getText()
String currentBuildScriptHash = getVersionHash(currentBuildScript)
String availableBuildScript = availableBuildScriptUrl().newInputStream(parameters).getText()
String availableBuildScriptHash = getVersionHash(availableBuildScript)
boolean isUpToDate = currentBuildScriptHash.empty || availableBuildScriptHash.empty || currentBuildScriptHash == availableBuildScriptHash
return !isUpToDate
}
static String getVersionHash(String buildScriptContent) {
String versionLine = buildScriptContent.find("^//version: [a-z0-9]*")
if(versionLine != null) {
return versionLine.split(": ").last()
}
return ""
}
configure(updateBuildScript) {
group = 'forgegradle'
description = 'Updates the build script to the latest version'
} }
+11 -1
View File
@@ -1,5 +1,15 @@
// Add your dependencies here // Add your dependencies here
dependencies { dependencies {
compile("com.github.GTNewHorizons:NotEnoughItems:master-SNAPSHOT:dev") implementation("com.github.GTNewHorizons:CodeChickenCore:1.4.19:dev")
compileOnly("com.cardinalstar.cubicchunks:CubicChunks1710:v0.1.8-alpha:dev")
compileOnly("com.github.GTNewHorizons:Angelica:2.1.54:dev")
runtimeOnlyNonPublishable("com.github.GTNewHorizons:Hodgepodge:2.7.174:dev")
compileOnly("com.github.GTNewHorizons:Postea:1.2.5:dev") {transitive = false}
devOnlyNonPublishable("com.github.GTNewHorizons:NotEnoughItems:2.8.114-GTNH:dev") {
exclude group: 'com.github.GTNewHorizons', module: 'CodeChickenCore'
}
compileOnly("com.github.GTNewHorizons:GTNHLib:0.11.44:dev")
// devOnlyNonPublishable("com.github.GTNewHorizons:Angelica:2.2.10:dev")
devOnlyNonPublishable("io.github.legacymoddingmc:unimixins:0.1.23:dev")
} }
+209 -33
View File
@@ -1,59 +1,235 @@
# ExampleMod tag to use as Blowdryer (Spotless, etc.) settings version, leave empty to disable.
# LOCAL to test local config updates.
gtnh.settings.blowdryerTag = 0.2.0
# Human-readable mod name, available for mcmod.info population.
modName = Forge Multipart modName = Forge Multipart
# This is a case-sensitive string to identify your mod. Convention is to use lower case. # Case-sensitive identifier string, available for mcmod.info population and used for automatic mixin JSON generation.
# Conventionally lowercase.
modId = ForgeMultipart modId = ForgeMultipart
# Root package of the mod, used to find various classes in other properties,
# mcmod.info substitution, enabling assertions in run tasks, etc.
modGroup = codechicken modGroup = codechicken
# WHY is there no version field? # Whether to use modGroup as the maven publishing group.
# The build script relies on git to provide a version via tags. It is super easy and will enable you to always know the # When false, com.github.GTNewHorizons is used.
# code base or your binary. Check out this tutorial: https://blog.mattclemente.com/2017/10/13/versioning-with-git-tags/ useModGroupForPublishing = false
# Will update your build.gradle automatically whenever an update is available
# Updates your build.gradle and settings.gradle automatically whenever an update is available.
autoUpdateBuildScript = false autoUpdateBuildScript = false
# Version of Minecraft to target
minecraftVersion = 1.7.10 minecraftVersion = 1.7.10
# Version of Minecraft Forge to target
forgeVersion = 10.13.4.1614 forgeVersion = 10.13.4.1614
# Select a username for testing your mod with breakpoints. You may leave this empty for a random user name each time you # Specify an MCP channel for dependency deobfuscation and the deobfParams task.
# restart Minecraft in development. Choose this dependent on your mod: channel = stable
# Do you need consistent player progressing (for example Thaumcraft)? -> Select a name
# Do you need to test how your custom blocks interacts with a player that is not the owner? -> leave name empty
developmentEnvironmentUserName = "Developer"
# Define a source file of your project with: # Specify an MCP mappings version for dependency deobfuscation and the deobfParams task.
mappingsVersion = 12
# Defines other MCP mappings for dependency deobfuscation.
remoteMappings = https\://raw.githubusercontent.com/MinecraftForge/FML/1.7.10/conf/
# Select a default username for testing your mod. You can always override this per-run by running
# `./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
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
# Generate a class with a String field for the mod version named as defined below.
# If generateGradleTokenClass is empty or not missing, no such class will be generated.
# If gradleTokenVersion is empty or missing, the field will not be present in the class.
generateGradleTokenClass = codechicken.multipart.Tags
# Name of the token containing the project's current version to generate/replace.
gradleTokenVersion = VERSION
# [DEPRECATED] Mod ID replacement token.
gradleTokenModId =
# [DEPRECATED] Mod name replacement token.
gradleTokenModName =
# [DEPRECATED] Mod Group replacement token.
gradleTokenGroupName =
# [DEPRECATED]
# Multiple source files can be defined here by providing a comma-separated list: Class1.java,Class2.java,Class3.java
# public static final String VERSION = "GRADLETOKEN_VERSION"; # public static final String VERSION = "GRADLETOKEN_VERSION";
# The string's content will be replaced with your mods version when compiled. You should use this to specify your mod's # The string's content will be replaced with your mod's version when compiled. You should use this to specify your mod's
# version in @Mod([...], version = VERSION, [...]) # version in @Mod([...], version = VERSION, [...]).
# Leave these properties empty to skip individual token replacements # Leave these properties empty to skip individual token replacements.
replaceGradleTokenInFile = Tags.java replaceGradleTokenInFile =
gradleTokenModId = GRADLETOKEN_MODID
gradleTokenModName = GRADLETOKEN_MODNAME
gradleTokenVersion = GRADLETOKEN_VERSION
gradleTokenGroupName = GRADLETOKEN_GROUPNAME
# In case your mod provides an API for other mods to implement you may declare its package here. Otherwise you can # In case your mod provides an API for other mods to implement you may declare its package here. Otherwise, you can
# leave this property empty. # leave this property empty.
# Example value: apiPackage = api + modGroup = com.myname.mymodid -> com.myname.mymodid.api # Example value: (apiPackage = api) + (modGroup = com.myname.mymodid) -> com.myname.mymodid.api
apiPackage = apiPackage =
# Specify the configuration file for Forge's access transformers here. I must be placed into /src/main/resources/META-INF/ # Specify the configuration file for Forge's access transformers here. It must be placed into /src/main/resources/META-INF/
# Example value: mymodid_at.cfg # There can be multiple files in a space-separated list.
accessTransformersFile = # Example value: mymodid_at.cfg nei_at.cfg
accessTransformersFile = multipart_at.cfg
# Provides setup for Mixins if enabled. If you don't know what mixins are: Keep it disabled! # Provides setup for Mixins if enabled. If you don't know what mixins are: Keep it disabled!
usesMixins = false usesMixins = true
# Specify the location of your implementation of IMixinPlugin. Leave it empty otherwise.
# Set to a non-empty string to configure mixins in a separate source set under src/VALUE, instead of src/main.
# This can speed up compile times thanks to not running the mixin annotation processor on all input sources.
# Mixin classes will have access to "main" classes, but not the other way around.
separateMixinSourceSet = mixin
# Adds some debug arguments like verbose output and class export.
usesMixinDebug = true
# Specify the location of your implementation of IMixinConfigPlugin. Leave it empty otherwise.
mixinPlugin = mixinPlugin =
# Specify the package that contains all of your Mixins. You may only place Mixins in this package or the build will fail!
mixinsPackage = # Specify the package that contains all of your Mixins. The package must exist or
# the build will fail. If you have a package property defined in your mixins.<modid>.json,
# it must match with this or the build will fail.
mixinsPackage = multipart.mixin
# Specify the core mod entry class if you use a core mod. This class must implement IFMLLoadingPlugin! # Specify the core mod entry class if you use a core mod. This class must implement IFMLLoadingPlugin!
# This parameter is for legacy compatability only # This parameter is for legacy compatibility only
# Example value: coreModClass = asm.FMLPlugin + modGroup = com.myname.mymodid -> com.myname.mymodid.asm.FMLPlugin # Example value: (coreModClass = asm.FMLPlugin) + (modGroup = com.myname.mymodid) -> com.myname.mymodid.asm.FMLPlugin
coreModClass = core.launch.DepLoader coreModClass = multipart.mixin.FMPMixinLoader
# If your project is only a consolidation of mixins or a core mod and does NOT contain a 'normal' mod ( = some class # If your project is only a consolidation of mixins or a core mod and does NOT contain a 'normal' mod ( = some class
# that is annotated with @Mod) you want this to be true. When in doubt: leave it on false! # that is annotated with @Mod) you want this to be true. When in doubt: leave it on false!
containsMixinsAndOrCoreModOnly = false containsMixinsAndOrCoreModOnly = false
# If enabled, you may use 'shadowImplementation' for dependencies. They will be integrated in your jar. It is your # Enables Mixins even if this mod doesn't use them, useful if one of the dependencies uses mixins.
# responsibility check the licence and request permission for distribution, if required. forceEnableMixins = false
# If enabled, you may use 'shadowCompile' for dependencies. They will be integrated into your jar. It is your
# responsibility to check the license and request permission for distribution if required.
usesShadowedDependencies = false usesShadowedDependencies = false
# If disabled, won't remove unused classes from shadowed dependencies. Some libraries use reflection to access
# their own classes, making the minimization unreliable.
minimizeShadowedDependencies = true
# If disabled, won't rename the shadowed classes.
relocateShadowedDependencies = true
# Adds CurseMaven, Modrinth, and some more well-known 1.7.10 repositories.
includeWellKnownRepositories = true
# A list of repositories to exclude from the includeWellKnownRepositories setting. Should be a space separated
# list of strings, with the acceptable keys being(case does not matter):
# cursemaven
# modrinth
excludeWellKnownRepositories =
# Change these to your Maven coordinates if you want to publish to a custom Maven repository instead of the default GTNH Maven.
# Authenticate with the MAVEN_USER and MAVEN_PASSWORD environment variables.
# If you need a more complex setup disable maven publishing here and add a publishing repository to addon.gradle.
usesMavenPublishing = true
# Maven repository to publish the mod to.
# mavenPublishUrl = https\://nexus.gtnewhorizons.com/repository/releases/
# Publishing to Modrinth requires you to set the MODRINTH_TOKEN environment variable to your current Modrinth API token.
#
# The project's ID on Modrinth. Can be either the slug or the ID.
# Leave this empty if you don't want to publish to Modrinth.
modrinthProjectId =
# The project's relations on Modrinth. You can use this to refer to other projects on Modrinth.
# Syntax: scope1-type1:name1;scope2-type2:name2;...
# Where scope can be one of [required, optional, incompatible, embedded],
# type can be one of [project, version],
# and the name is the Modrinth project or version slug/id of the other mod.
# Example: required-project:fplib;optional-project:gasstation;incompatible-project:gregtech
# Note: UniMixins is automatically set as a required dependency if usesMixins = true.
modrinthRelations =
# Publishing to CurseForge requires you to set the CURSEFORGE_TOKEN environment variable to one of your CurseForge API tokens.
#
# The project's numeric ID on CurseForge. You can find this in the About Project box.
# Leave this empty if you don't want to publish on CurseForge.
curseForgeProjectId =
# The project's relations on CurseForge. You can use this to refer to other projects on CurseForge.
# Syntax: type1:name1;type2:name2;...
# Where type can be one of [requiredDependency, embeddedLibrary, optionalDependency, tool, incompatible],
# and the name is the CurseForge project slug of the other mod.
# Example: requiredDependency:railcraft;embeddedLibrary:cofhlib;incompatible:buildcraft
# Note: UniMixins is automatically set as a required dependency if usesMixins = true.
curseForgeRelations =
# Optional parameter to customize the produced artifacts. Use this to preserve artifact naming when migrating older
# projects. New projects should not use this parameter.
# customArchiveBaseName =
# Optional parameter to customize the default working directory used by the runClient* tasks. Relative to the project directory.
# runClientWorkingDirectory = run/client
# Optional parameter to customize the default working directory used by the runServer* tasks. Relative to the project directory.
# runServerWorkingDirectory = run/server
# Optional parameter to have the build automatically fail if an illegal version is used.
# This can be useful if you e.g. only want to allow versions in the form of '1.1.xxx'.
# The check is ONLY performed if the version is a git tag.
# Note: the specified string must be escaped, so e.g. 1\\.1\\.\\d+ instead of 1\.1\.\d+
# versionPattern =
# Uncomment to prevent the source code from being published.
# noPublishedSources = true
# Uncomment this to disable Spotless checks.
# This should only be uncommented to keep it easier to sync with upstream/other forks.
# That is, if there is no other active fork/upstream, NEVER change this.
# disableSpotless = true
# Uncomment this to disable Checkstyle checks (currently wildcard import check).
# disableCheckstyle = true
# Override the IDEA build type. Valid values are: "" (leave blank, do not override), "idea" (force use native IDEA build), "gradle"
# (force use delegated build).
# This is meant to be set in $HOME/.gradle/gradle.properties.
# e.g. add "systemProp.org.gradle.project.ideaOverrideBuildType=idea" will override the build type to be native build.
# WARNING: If you do use this option, it will overwrite whatever you have in your existing projects. This might not be what you want!
# Usually there is no need to uncomment this here as other developers do not necessarily use the same build type as you.
# ideaOverrideBuildType = idea
# Whether IDEA should run spotless checks when pressing the Build button.
# This is meant to be set in $HOME/.gradle/gradle.properties.
# ideaCheckSpotlessOnBuild = true
+12
View File
@@ -0,0 +1,12 @@
#This file is generated by updateDaemonJvm
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/1630f7ebef05444cb27a2709ea0249b3/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/fa1e318c287360478e3c83a9a3ef1007/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/1630f7ebef05444cb27a2709ea0249b3/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/fa1e318c287360478e3c83a9a3ef1007/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c2dd35c9d0aaf0ba6ad0791320f99dfc/redirect
toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/e5810bd7fd1f8a586644409d395a7e55/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/1630f7ebef05444cb27a2709ea0249b3/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/fa1e318c287360478e3c83a9a3ef1007/redirect
toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/7b3c4877c0749019e6805bb61e421497/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/8e1d9ee5d0f13e442218f6884a306da1/redirect
toolchainVersion=25
Binary file not shown.
+3 -1
View File
@@ -1,5 +1,7 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.9.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
Vendored
+178 -118
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env sh #!/bin/sh
# #
# Copyright 2015 the original author or authors. # Copyright © 2015 the original authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -15,80 +15,114 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
# #
# SPDX-License-Identifier: Apache-2.0
#
############################################################################## ##############################################################################
## #
## Gradle start up script for UN*X # Gradle start up script for POSIX generated by Gradle.
## #
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/b631911858264c0b6e4d6603d677ff5218766cee/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
############################################################################## ##############################################################################
# Attempt to set APP_HOME # Attempt to set APP_HOME
# Resolve links: $0 may be a link # Resolve links: $0 may be a link
PRG="$0" app_path=$0
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do # Need this for daisy-chained symlinks.
ls=`ls -ld "$PRG"` while
link=`expr "$ls" : '.*-> \(.*\)$'` APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
if expr "$link" : '/.*' > /dev/null; then [ -h "$app_path" ]
PRG="$link" do
else ls=$( ls -ld "$app_path" )
PRG=`dirname "$PRG"`"/$link" link=${ls#*' -> '}
fi case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle" # This is normally unused
APP_BASE_NAME=`basename "$0"` # shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum" MAX_FD=maximum
warn () { warn () {
echo "$*" echo "$*"
} } >&2
die () { die () {
echo echo
echo "$*" echo "$*"
echo echo
exit 1 exit 1
} } >&2
# OS specific support (must be 'true' or 'false'). # OS specific support (must be 'true' or 'false').
cygwin=false cygwin=false
msys=false msys=false
darwin=false darwin=false
nonstop=false nonstop=false
case "`uname`" in case "$( uname )" in #(
CYGWIN* ) CYGWIN* ) cygwin=true ;; #(
cygwin=true Darwin* ) darwin=true ;; #(
;; MSYS* | MINGW* ) msys=true ;; #(
Darwin* ) NONSTOP* ) nonstop=true ;;
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM. # Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables # IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java" JAVACMD=$JAVA_HOME/jre/sh/java
else else
JAVACMD="$JAVA_HOME/bin/java" JAVACMD=$JAVA_HOME/bin/java
fi fi
if [ ! -x "$JAVACMD" ] ; then if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -97,92 +131,118 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi fi
else else
JAVACMD="java" JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
MAX_FD_LIMIT=`ulimit -H -n` case $MAX_FD in #(
if [ $? -eq 0 ] ; then max*)
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
MAX_FD="$MAX_FD_LIMIT" # shellcheck disable=SC2039,SC3045
fi MAX_FD=$( ulimit -H -n ) ||
ulimit -n $MAX_FD warn "Could not query maximum file descriptor limit"
if [ $? -ne 0 ] ; then esac
warn "Could not set maximum file descriptor limit: $MAX_FD" case $MAX_FD in #(
fi '' | soft) :;; #(
else *)
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
fi # shellcheck disable=SC2039,SC3045
fi ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac esac
fi fi
# Escape application args # Collect all arguments for the java command, stacking in reverse order:
save () { # * args from the command line
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done # * the main class name
echo " " # * -classpath
} # * -D...appname settings
APP_ARGS=$(save "$@") # * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# Collect all arguments for the java command, following the shell quoting and substitution rules # For Cygwin or MSYS, switch paths to Windows format before running java
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong JAVACMD=$( cygpath --unix "$JAVACMD" )
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")" # Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@" exec "$JAVACMD" "$@"
Vendored
+27 -34
View File
@@ -13,8 +13,10 @@
@rem See the License for the specific language governing permissions and @rem See the License for the specific language governing permissions and
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%" == "" @echo off @if "%DEBUG%"=="" @echo off
@rem ########################################################################## @rem ##########################################################################
@rem @rem
@rem Gradle startup script for Windows @rem Gradle startup script for Windows
@@ -25,10 +27,14 @@
if "%OS%"=="Windows_NT" setlocal if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=. if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@@ -37,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init if %ERRORLEVEL% equ 0 goto execute
echo. echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. echo location of your Java installation. 1>&2
goto fail goto fail
@@ -51,48 +57,35 @@ goto fail
set JAVA_HOME=%JAVA_HOME:"=% set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init if exist "%JAVA_EXE%" goto execute
echo. echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. echo location of your Java installation. 1>&2
goto fail goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute :execute
@rem Setup the command line @rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle @rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd if %ERRORLEVEL% equ 0 goto mainEnd
:fail :fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code! rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 set EXIT_CODE=%ERRORLEVEL%
exit /b 1 if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd :mainEnd
if "%OS%"=="Windows_NT" endlocal if "%OS%"=="Windows_NT" endlocal
+1 -3
View File
@@ -1,7 +1,5 @@
// Add any additional repositiroes for your dependencies here // Add any additional repositiroes for your dependencies here
repositories { repositories {
maven { mavenLocal()
url = "https://jitpack.io"
}
} }
+21
View File
@@ -0,0 +1,21 @@
pluginManagement {
repositories {
maven {
// RetroFuturaGradle
name "GTNH Maven"
url "https://nexus.gtnewhorizons.com/repository/public/"
mavenContent {
includeGroup("com.gtnewhorizons")
includeGroupByRegex("com\\.gtnewhorizons\\..+")
}
}
gradlePluginPortal()
mavenCentral()
mavenLocal()
}
}
plugins {
id 'com.gtnewhorizons.gtnhsettingsconvention' version '2.0.24'
}
@@ -0,0 +1,47 @@
package codechicken.multipart.mixin;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.gtnewhorizon.gtnhmixins.IEarlyMixinLoader;
import com.gtnewhorizon.gtnhmixins.builders.IMixins;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin;
@IFMLLoadingPlugin.MCVersion("1.7.10")
public class FMPMixinLoader implements IFMLLoadingPlugin, IEarlyMixinLoader {
@Override
public String[] getASMTransformerClass() {
return null;
}
@Override
public String getModContainerClass() {
return null;
}
@Override
public String getSetupClass() {
return null;
}
@Override
public void injectData(Map<String, Object> data) {}
@Override
public String getAccessTransformerClass() {
return null;
}
@Override
public String getMixinConfig() {
return "mixins.ForgeMultipart.early.json";
}
@Override
public List<String> getMixins(Set<String> loadedCoreMods) {
return IMixins.getEarlyMixins(Mixins.class, loadedCoreMods);
}
}
@@ -0,0 +1,24 @@
package codechicken.multipart.mixin;
import javax.annotation.Nonnull;
import com.gtnewhorizon.gtnhmixins.builders.IMixins;
import com.gtnewhorizon.gtnhmixins.builders.MixinBuilder;
public enum Mixins implements IMixins {
RENDER_GLOBAL_MIXIN(new MixinBuilder("Redirects part block break renders to ISBRHModel")
.addClientMixins("MixinRenderGlobal").addRequiredMod(TargetedMod.GTNHLIB).setPhase(Phase.EARLY));
private final MixinBuilder builder;
Mixins(MixinBuilder builder) {
this.builder = builder;
}
@Nonnull
@Override
public MixinBuilder getBuilder() {
return this.builder;
}
}
@@ -0,0 +1,31 @@
package codechicken.multipart.mixin;
import javax.annotation.Nonnull;
import com.gtnewhorizon.gtnhmixins.builders.ITargetMod;
import com.gtnewhorizon.gtnhmixins.builders.TargetModBuilder;
public enum TargetedMod implements ITargetMod {
GTNHLIB("GTNHLib Core", "gtnhlib");
private final TargetModBuilder builder;
TargetedMod(String modId) {
this(null, modId, null);
}
TargetedMod(String coreModClass, String modId) {
this(coreModClass, modId, null);
}
TargetedMod(String coreModClass, String modId, String targetClass) {
this.builder = new TargetModBuilder().setCoreModClass(coreModClass).setModId(modId).setTargetClass(targetClass);
}
@Nonnull
@Override
public TargetModBuilder getBuilder() {
return builder;
}
}
@@ -0,0 +1 @@
public net.minecraft.block.BlockButton func_150043_b(I)V #function that sets up hitboxes for that meta
Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 KiB

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 531 B

After

Width:  |  Height:  |  Size: 500 B

@@ -6,6 +6,8 @@ item.microblock:sawIron.name=Iron Saw
item.microblock:sawDiamond.name=Diamond Saw item.microblock:sawDiamond.name=Diamond Saw
item.microblock:stoneRod.name=Stone Rod item.microblock:stoneRod.name=Stone Rod
item.microblock.name=Microblock
mcr_face.1.name=%s Cover mcr_face.1.name=%s Cover
mcr_face.1.subset=Cover mcr_face.1.subset=Cover
mcr_face.2.name=%s Panel mcr_face.2.name=%s Panel
@@ -35,3 +37,5 @@ mcr_cnr.4.name=%s Notch
mcr_cnr.4.subset=Notch mcr_cnr.4.subset=Notch
nei.subsets.Microblocks=Microblocks nei.subsets.Microblocks=Microblocks
key.control=Switch block disposition
@@ -34,4 +34,4 @@ mcr_cnr.2.subset=Coin
mcr_cnr.4.name=Encoche de/d' %s mcr_cnr.4.name=Encoche de/d' %s
mcr_cnr.4.subset=Encoche mcr_cnr.4.subset=Encoche
key.control=[Forge Multipart] Disposition du bloc key.control=Disposition du bloc
@@ -34,6 +34,6 @@ mcr_cnr.2.subset=Angoletto
mcr_cnr.4.name=Angolo di %s mcr_cnr.4.name=Angolo di %s
mcr_cnr.4.subset=Angolo mcr_cnr.4.subset=Angolo
key.control=[Forge Multipart] Disposizione del blocco key.control=Disposizione del blocco
nei.subsets.Microblocks=Microblocchi nei.subsets.Microblocks=Microblocchi
-6
View File
@@ -1,6 +0,0 @@
{
"repo": "http://files.minecraftforge.net/maven/codechicken/CodeChickenLib/${mc_version}-${ccl_version}/",
"file": "CodeChickenLib-${mc_version}-${ccl_version}-universal.jar",
"dev": "CodeChickenLib-${mc_version}-${ccl_version}-dev.jar",
"class": "codechicken.lib.asm.ASMHelper"
}
@@ -0,0 +1,11 @@
{
"required": true,
"minVersion": "0.8.5-GTNH",
"package": "codechicken.multipart.mixin.early",
"refmap": "mixins.ForgeMultipart.refmap.json",
"target": "@env(DEFAULT)",
"mixinextras": {
"minVersion": "0.5.0"
},
"compatibilityLevel": "JAVA_8"
}
@@ -0,0 +1,7 @@
{
"required": true,
"minVersion": "0.8.5-GTNH",
"refmap": "mixins.ForgeMultipart.refmap.json",
"target": "@env(DEFAULT)",
"compatibilityLevel": "JAVA_8"
}
@@ -1,618 +0,0 @@
package codechicken.core.launch;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import cpw.mods.fml.common.versioning.ComparableVersion;
import cpw.mods.fml.relauncher.FMLInjectionData;
import cpw.mods.fml.relauncher.FMLLaunchHandler;
import cpw.mods.fml.relauncher.IFMLCallHook;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin;
import net.minecraft.launchwrapper.LaunchClassLoader;
import sun.misc.URLClassPath;
import sun.net.util.URLUtil;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.awt.*;
import java.awt.Dialog.ModalityType;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.*;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* For autodownloading stuff.
* This is really unoriginal, mostly ripped off FML, credits to cpw.
*/
public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook {
private static ByteBuffer downloadBuffer = ByteBuffer.allocateDirect(1 << 23);
private static final String owner = "CB's DepLoader";
private static DepLoadInst inst;
public interface IDownloadDisplay {
void resetProgress(int sizeGuess);
void setPokeThread(Thread currentThread);
void updateProgress(int fullLength);
boolean shouldStopIt();
void updateProgressString(String string, Object... data);
Object makeDialog();
void showErrorDialog(String name, String url);
}
@SuppressWarnings("serial")
public static class Downloader extends JOptionPane implements IDownloadDisplay {
private JDialog container;
private JLabel currentActivity;
private JProgressBar progress;
boolean stopIt;
Thread pokeThread;
private Box makeProgressPanel() {
Box box = Box.createVerticalBox();
box.add(Box.createRigidArea(new Dimension(0, 10)));
JLabel welcomeLabel = new JLabel("<html><b><font size='+1'>" + owner + " is setting up your minecraft environment</font></b></html>");
box.add(welcomeLabel);
welcomeLabel.setAlignmentY(LEFT_ALIGNMENT);
welcomeLabel = new JLabel("<html>Please wait, " + owner + " has some tasks to do before you can play</html>");
welcomeLabel.setAlignmentY(LEFT_ALIGNMENT);
box.add(welcomeLabel);
box.add(Box.createRigidArea(new Dimension(0, 10)));
currentActivity = new JLabel("Currently doing ...");
box.add(currentActivity);
box.add(Box.createRigidArea(new Dimension(0, 10)));
progress = new JProgressBar(0, 100);
progress.setStringPainted(true);
box.add(progress);
box.add(Box.createRigidArea(new Dimension(0, 30)));
return box;
}
@Override
public JDialog makeDialog() {
if (container != null)
return container;
setMessageType(JOptionPane.INFORMATION_MESSAGE);
setMessage(makeProgressPanel());
setOptions(new Object[]{"Stop"});
addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getSource() == Downloader.this && evt.getPropertyName() == VALUE_PROPERTY) {
requestClose("This will stop minecraft from launching\nAre you sure you want to do this?");
}
}
});
container = new JDialog(null, "Hello", ModalityType.MODELESS);
container.setResizable(false);
container.setLocationRelativeTo(null);
container.add(this);
this.updateUI();
container.pack();
container.setMinimumSize(container.getPreferredSize());
container.setVisible(true);
container.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
container.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
requestClose("Closing this window will stop minecraft from launching\nAre you sure you wish to do this?");
}
});
return container;
}
protected void requestClose(String message) {
int shouldClose = JOptionPane.showConfirmDialog(container, message, "Are you sure you want to stop?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (shouldClose == JOptionPane.YES_OPTION)
container.dispose();
stopIt = true;
if (pokeThread != null)
pokeThread.interrupt();
}
@Override
public void updateProgressString(String progressUpdate, Object... data) {
//FMLLog.finest(progressUpdate, data);
if (currentActivity != null)
currentActivity.setText(String.format(progressUpdate, data));
}
@Override
public void resetProgress(int sizeGuess) {
if (progress != null)
progress.getModel().setRangeProperties(0, 0, 0, sizeGuess, false);
}
@Override
public void updateProgress(int fullLength) {
if (progress != null)
progress.getModel().setValue(fullLength);
}
@Override
public void setPokeThread(Thread currentThread) {
this.pokeThread = currentThread;
}
@Override
public boolean shouldStopIt() {
return stopIt;
}
@Override
public void showErrorDialog(String name, String url) {
JEditorPane ep = new JEditorPane("text/html",
"<html>" +
owner + " was unable to download required library " + name +
"<br>Check your internet connection and try restarting or download it manually from" +
"<br><a href=\"" + url + "\">" + url + "</a> and put it in your mods folder" +
"</html>");
ep.setEditable(false);
ep.setOpaque(false);
ep.addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent event) {
try {
if (event.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED))
Desktop.getDesktop().browse(event.getURL().toURI());
} catch (Exception e) {
}
}
});
JOptionPane.showMessageDialog(null, ep, "A download error has occured", JOptionPane.ERROR_MESSAGE);
}
}
public static class DummyDownloader implements IDownloadDisplay {
@Override
public void resetProgress(int sizeGuess) {
}
@Override
public void setPokeThread(Thread currentThread) {
}
@Override
public void updateProgress(int fullLength) {
}
@Override
public boolean shouldStopIt() {
return false;
}
@Override
public void updateProgressString(String string, Object... data) {
}
@Override
public Object makeDialog() {
return null;
}
@Override
public void showErrorDialog(String name, String url) {
}
}
public static class VersionedFile
{
public final Pattern pattern;
public final String filename;
public final ComparableVersion version;
public final String name;
public VersionedFile(String filename, Pattern pattern) {
this.pattern = pattern;
this.filename = filename;
Matcher m = pattern.matcher(filename);
if(m.matches()) {
name = m.group(1);
version = new ComparableVersion(m.group(2));
}
else {
name = null;
version = null;
}
}
public boolean matches() {
return name != null;
}
}
public static class Dependency
{
public String url;
public VersionedFile file;
public String existing;
/**
* Flag set to add this dep to the classpath immediately because it is required for a coremod.
*/
public boolean coreLib;
public Dependency(String url, VersionedFile file, boolean coreLib) {
this.url = url;
this.file = file;
this.coreLib = coreLib;
}
}
public static class DepLoadInst {
private File modsDir;
private File v_modsDir;
private IDownloadDisplay downloadMonitor;
private JDialog popupWindow;
private Map<String, Dependency> depMap = new HashMap<String, Dependency>();
private HashSet<String> depSet = new HashSet<String>();
public DepLoadInst() {
String mcVer = (String) FMLInjectionData.data()[4];
File mcDir = (File) FMLInjectionData.data()[6];
modsDir = new File(mcDir, "mods");
v_modsDir = new File(mcDir, "mods/" + mcVer);
if (!v_modsDir.exists())
v_modsDir.mkdirs();
}
private void addClasspath(String name) {
try {
((LaunchClassLoader) DepLoader.class.getClassLoader()).addURL(new File(v_modsDir, name).toURI().toURL());
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
private void deleteMod(File mod) {
if (mod.delete())
return;
try {
ClassLoader cl = DepLoader.class.getClassLoader();
URL url = mod.toURI().toURL();
Field f_ucp = URLClassLoader.class.getDeclaredField("ucp");
Field f_loaders = URLClassPath.class.getDeclaredField("loaders");
Field f_lmap = URLClassPath.class.getDeclaredField("lmap");
f_ucp.setAccessible(true);
f_loaders.setAccessible(true);
f_lmap.setAccessible(true);
URLClassPath ucp = (URLClassPath) f_ucp.get(cl);
Closeable loader = ((Map<String, Closeable>) f_lmap.get(ucp)).remove(URLUtil.urlNoFragString(url));
if (loader != null) {
loader.close();
((List<?>) f_loaders.get(ucp)).remove(loader);
}
} catch (Exception e) {
e.printStackTrace();
}
if (!mod.delete()) {
mod.deleteOnExit();
String msg = owner + " was unable to delete file " + mod.getPath() + " the game will now try to delete it on exit. If this dialog appears again, delete it manually.";
System.err.println(msg);
if (!GraphicsEnvironment.isHeadless())
JOptionPane.showMessageDialog(null, msg, "An update error has occured", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
private void download(Dependency dep) {
popupWindow = (JDialog) downloadMonitor.makeDialog();
File libFile = new File(v_modsDir, dep.file.filename);
try {
URL libDownload = new URL(dep.url + '/' + dep.file.filename);
downloadMonitor.updateProgressString("Downloading file %s", libDownload.toString());
System.out.format("Downloading file %s\n", libDownload.toString());
URLConnection connection = libDownload.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setRequestProperty("User-Agent", "" + owner + " Downloader");
int sizeGuess = connection.getContentLength();
download(connection.getInputStream(), sizeGuess, libFile);
downloadMonitor.updateProgressString("Download complete");
System.out.println("Download complete");
scanDepInfo(libFile);
} catch (Exception e) {
libFile.delete();
if (downloadMonitor.shouldStopIt()) {
System.err.println("You have stopped the downloading operation before it could complete");
System.exit(1);
return;
}
downloadMonitor.showErrorDialog(dep.file.filename, dep.url + '/' + dep.file.filename);
throw new RuntimeException("A download error occured", e);
}
}
private void download(InputStream is, int sizeGuess, File target) throws Exception {
if (sizeGuess > downloadBuffer.capacity())
throw new Exception(String.format("The file %s is too large to be downloaded by " + owner + " - the download is invalid", target.getName()));
downloadBuffer.clear();
int bytesRead, fullLength = 0;
downloadMonitor.resetProgress(sizeGuess);
try {
downloadMonitor.setPokeThread(Thread.currentThread());
byte[] smallBuffer = new byte[1024];
while ((bytesRead = is.read(smallBuffer)) >= 0) {
downloadBuffer.put(smallBuffer, 0, bytesRead);
fullLength += bytesRead;
if (downloadMonitor.shouldStopIt()) {
break;
}
downloadMonitor.updateProgress(fullLength);
}
is.close();
downloadMonitor.setPokeThread(null);
downloadBuffer.limit(fullLength);
downloadBuffer.position(0);
} catch (InterruptedIOException e) {
// We were interrupted by the stop button. We're stopping now.. clear interruption flag.
Thread.interrupted();
throw new Exception("Stop");
} catch (IOException e) {
throw e;
}
try {
/*String cksum = generateChecksum(downloadBuffer);
if (cksum.equals(validationHash))
{*/
if (!target.exists())
target.createNewFile();
downloadBuffer.position(0);
FileOutputStream fos = new FileOutputStream(target);
fos.getChannel().write(downloadBuffer);
fos.close();
/*}
else
{
throw new RuntimeException(String.format("The downloaded file %s has an invalid checksum %s (expecting %s). The download did not succeed correctly and the file has been deleted. Please try launching again.", target.getName(), cksum, validationHash));
}*/
} catch (Exception e) {
throw e;
}
}
private String checkExisting(Dependency dep) {
for (File f : modsDir.listFiles()) {
VersionedFile vfile = new VersionedFile(f.getName(), dep.file.pattern);
if (!vfile.matches() || !vfile.name.equals(dep.file.name))
continue;
if (f.renameTo(new File(v_modsDir, f.getName())))
continue;
deleteMod(f);
}
for (File f : v_modsDir.listFiles()) {
VersionedFile vfile = new VersionedFile(f.getName(), dep.file.pattern);
if (!vfile.matches() || !vfile.name.equals(dep.file.name))
continue;
int cmp = vfile.version.compareTo(dep.file.version);
if (cmp < 0) {
System.out.println("Deleted old version " + f.getName());
deleteMod(f);
return null;
}
if (cmp > 0) {
System.err.println("Warning: version of " + dep.file.name + ", " + vfile.version + " is newer than request " + dep.file.version);
return f.getName();
}
return f.getName();//found dependency
}
return null;
}
public void load() {
scanDepInfos();
if (depMap.isEmpty())
return;
loadDeps();
activateDeps();
}
private void activateDeps() {
for (Dependency dep : depMap.values())
if (dep.coreLib)
addClasspath(dep.existing);
}
private void loadDeps() {
downloadMonitor = FMLLaunchHandler.side().isClient() ? new Downloader() : new DummyDownloader();
try {
while (!depSet.isEmpty()) {
Iterator<String> it = depSet.iterator();
Dependency dep = depMap.get(it.next());
it.remove();
load(dep);
}
} finally {
if (popupWindow != null) {
popupWindow.setVisible(false);
popupWindow.dispose();
}
}
}
private void load(Dependency dep) {
dep.existing = checkExisting(dep);
if (dep.existing == null)//download dep
{
download(dep);
dep.existing = dep.file.filename;
}
}
private List<File> modFiles() {
List<File> list = new LinkedList<File>();
list.addAll(Arrays.asList(modsDir.listFiles()));
list.addAll(Arrays.asList(v_modsDir.listFiles()));
return list;
}
private void scanDepInfos() {
for (File file : modFiles()) {
if (!file.getName().endsWith(".jar") && !file.getName().endsWith(".zip"))
continue;
scanDepInfo(file);
}
}
private void scanDepInfo(File file) {
try {
ZipFile zip = new ZipFile(file);
ZipEntry e = zip.getEntry("dependancies.info");
if (e == null) e = zip.getEntry("dependencies.info");
if (e != null)
loadJSon(zip.getInputStream(e));
zip.close();
} catch (Exception e) {
System.err.println("Failed to load dependencies.info from " + file.getName() + " as JSON");
e.printStackTrace();
}
}
private void loadJSon(InputStream input) throws IOException {
InputStreamReader reader = new InputStreamReader(input);
JsonElement root = new JsonParser().parse(reader);
if (root.isJsonArray())
loadJSonArr(root);
else
loadJson(root.getAsJsonObject());
reader.close();
}
private void loadJSonArr(JsonElement root) throws IOException {
for (JsonElement node : root.getAsJsonArray())
loadJson(node.getAsJsonObject());
}
private void loadJson(JsonObject node) throws IOException {
boolean obfuscated = ((LaunchClassLoader) DepLoader.class.getClassLoader())
.getClassBytes("net.minecraft.world.World") == null;
String testClass = node.get("class").getAsString();
if (DepLoader.class.getResource("/" + testClass.replace('.', '/') + ".class") != null)
return;
String repo = node.get("repo").getAsString();
String filename = node.get("file").getAsString();
if (!obfuscated && node.has("dev"))
filename = node.get("dev").getAsString();
boolean coreLib = node.has("coreLib") && node.get("coreLib").getAsBoolean();
Pattern pattern = null;
try {
if(node.has("pattern"))
pattern = Pattern.compile(node.get("pattern").getAsString());
} catch (PatternSyntaxException e) {
System.err.println("Invalid filename pattern: "+node.get("pattern"));
e.printStackTrace();
}
if(pattern == null)
pattern = Pattern.compile("(\\w+).*?([\\d\\.]+)[-\\w]*\\.[^\\d]+");
VersionedFile file = new VersionedFile(filename, pattern);
if (!file.matches())
throw new RuntimeException("Invalid filename format for dependency: " + filename);
addDep(new Dependency(repo, file, coreLib));
}
private void addDep(Dependency newDep) {
if (mergeNew(depMap.get(newDep.file.name), newDep)) {
depMap.put(newDep.file.name, newDep);
depSet.add(newDep.file.name);
}
}
private boolean mergeNew(Dependency oldDep, Dependency newDep) {
if (oldDep == null)
return true;
Dependency newest = newDep.file.version.compareTo(oldDep.file.version) > 0 ? newDep : oldDep;
newest.coreLib = newDep.coreLib || oldDep.coreLib;
return newest == newDep;
}
}
public static void load() {
if (inst == null) {
inst = new DepLoadInst();
inst.load();
}
}
@Override
public String[] getASMTransformerClass() {
return null;
}
@Override
public String getModContainerClass() {
return null;
}
@Override
public String getSetupClass() {
return getClass().getName();
}
@Override
public void injectData(Map<String, Object> data) {
}
@Override
public Void call() {
load();
return null;
}
@Override
public String getAccessTransformerClass() {
return null;
}
}
@@ -0,0 +1,26 @@
package codechicken.microblock
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator
import net.coderbot.iris.Iris
import net.minecraft.block.Block
import net.minecraft.client.renderer.Tessellator
class AngelicaCompat {
def setShaderMaterialOverride(block: Block, meta: Int) = {
try {
if (Tessellator.instance.isInstanceOf[CapturingTessellator])
Iris.setShaderMaterialOverride(block, meta)
} catch {
case ex: ClassCastException => Unit
}
}
def resetShaderMaterialOverride() = {
try {
if (Tessellator.instance.isInstanceOf[CapturingTessellator])
Iris.resetShaderMaterialOverride()
} catch {
case ex: ClassCastException => Unit
}
}
}
@@ -8,132 +8,194 @@ import cpw.mods.fml.relauncher.Side
import net.minecraft.item.ItemStack import net.minecraft.item.ItemStack
import codechicken.lib.vec.{Cuboid6, Vector3} import codechicken.lib.vec.{Cuboid6, Vector3}
import net.minecraft.entity.player.EntityPlayer import net.minecraft.entity.player.EntityPlayer
import codechicken.lib.render.{CCRenderPipeline, ColourMultiplier, CCRenderState} import codechicken.lib.render.{
import codechicken.microblock.handler.MicroblockProxy CCRenderPipeline,
CCRenderState,
ColourMultiplier
}
import codechicken.microblock.handler.{MicroblockMod, MicroblockProxy}
import net.minecraft.entity.Entity import net.minecraft.entity.Entity
import codechicken.lib.render.uv.{UVTransformation, MultiIconTransformation} import codechicken.lib.render.uv.{MultiIconTransformation, UVTransformation}
import cpw.mods.fml.common.registry.{GameRegistry, GameData} import cpw.mods.fml.common.registry.{GameData, GameRegistry}
object MaterialRenderHelper import java.util.function.Supplier
{
private var pass = 0
private var builder:CCRenderPipeline#PipelineBuilder = _
def start(pos:Vector3, pass:Int, uvt:UVTransformation) = { private class ThreadState {
this.pass = pass var pass = 0
builder = CCRenderState.pipeline.builder() var builder: CCRenderPipeline#PipelineBuilder = _
builder.add(pos.translation()).add(uvt)
this
}
def blockColour(colour:Int) = {
builder.add(ColourMultiplier.instance(colour))
this
}
def lighting() = {
if(pass != -1)
builder.add(CCRenderState.lightMatrix)
this
}
def render() = builder.render()
} }
/** object MaterialRenderHelper {
* Standard micro material class suitable for most blocks. private val threadState =
*/ ThreadLocal.withInitial[ThreadState](new Supplier[ThreadState]() {
class BlockMicroMaterial(val block:Block, val meta:Int = 0) extends IMicroMaterial override def get(): ThreadState = new ThreadState()
{ })
val blockKey = Block.blockRegistry.getNameForObject(block) def pass = threadState.get().pass
def pass_=(pass: Int) = threadState.get().pass = pass
def builder = threadState.get().builder
def builder_=(builder: CCRenderPipeline#PipelineBuilder) =
threadState.get().builder = builder
@SideOnly(Side.CLIENT) def start(pos: Vector3, pass: Int, uvt: UVTransformation) = {
var icont:MultiIconTransformation = _ this.pass = pass
builder = CCRenderState.instance().pipeline.builder()
builder.add(pos.translation()).add(uvt)
this
}
@SideOnly(Side.CLIENT) def blockColour(colour: Int) = {
override def loadIcons() { builder.add(ColourMultiplier.instance(colour))
def safeIcon(block:Block, side:Int):IIcon = { this
try { }
return MicroblockProxy.renderBlocks.getIconSafe(block.getIcon(side, meta))
}
catch {
case e:Exception =>
}
return MicroblockProxy.renderBlocks.getIconSafe(null)
}
val iblock = Block.getBlockFromName(blockKey)//reacquire block instance incase a mod replcaed it def lighting() = {
icont = new MultiIconTransformation(Array.tabulate(6)(side => safeIcon(iblock, side)):_*) if (pass != -1)
} builder.add(CCRenderState.instance().lightMatrix)
this
}
def renderMicroFace(pos:Vector3, pass:Int, bounds:Cuboid6) { def blockAndMeta(b: Block, meta: Int) = {
MaterialRenderHelper.start(pos, pass, icont).blockColour(getColour(pass)).lighting().render() if (MicroblockMod.angelicaCompat != null)
} MicroblockMod.angelicaCompat.setShaderMaterialOverride(b, meta)
this
}
def getColour(pass:Int) = { def render(): Unit = {
if(pass == -1) builder.render()
block.getBlockColor<<8|0xFF if (MicroblockMod.angelicaCompat != null)
else { MicroblockMod.angelicaCompat.resetShaderMaterialOverride()
val pos = CCRenderState.lightMatrix.pos }
block.colorMultiplier(CCRenderState.lightMatrix.access, pos.x, pos.y, pos.z)<<8|0xFF
}
}
override def canRenderInPass(pass:Int) = block.canRenderInPass(pass)
@SideOnly(Side.CLIENT)
def getBreakingIcon(side:Int) = block.getIcon(side, meta)
def getItem = new ItemStack(block, 1, meta)
def getLocalizedName = getItem.getDisplayName
def getStrength(player:EntityPlayer) = {
var hardness = 30F
try {
hardness = block.getBlockHardness(null, 0, 0, 0)
} catch {
case e:Exception =>
}
player.getBreakSpeed(block, false, meta%16, 0, -1, 0) / hardness
}
def isTransparent = !block.isOpaqueCube
def getLightValue = block.getLightValue
def toolClasses = Seq("axe", "pickaxe", "shovel")
// meta > 15 will throw ArrayIndexOutOfBoundsException
def getCutterStrength = block.getHarvestLevel(meta % 16)
def getSound = block.stepSound
def explosionResistance(entity:Entity):Float = block.getExplosionResistance(entity)
} }
/** /** Standard micro material class suitable for most blocks.
* Utility functions for cleaner registry code */
*/ class BlockMicroMaterial(val block: Block, val meta: Int = 0)
object BlockMicroMaterial extends IMicroMaterial {
{ val blockKey = Block.blockRegistry.getNameForObject(block)
def oldKey(block:Block) = block.getUnlocalizedName
def materialKey(block:Block) = Block.blockRegistry.getNameForObject(block)
def materialKey(name:String, meta:Int) = name+(if(meta > 0) "_"+meta else "")
def materialKey(block:Block, meta:Int):String = materialKey(materialKey(block), meta)
def createAndRegister(block:Block, meta:Int, name:String) = @SideOnly(Side.CLIENT)
MicroMaterialRegistry.registerMaterial(new BlockMicroMaterial(block, meta), materialKey(name, meta)) var icont: MultiIconTransformation = _
def createAndRegister(block:Block, meta:Int, name:String, oldName:String) { @SideOnly(Side.CLIENT)
MicroMaterialRegistry.remapName(materialKey(oldName, meta), materialKey(name, meta)) override def loadIcons() {
createAndRegister(block, meta, name) def safeIcon(block: Block, side: Int): IIcon = {
try {
return MicroblockProxy.renderBlocks.getIconSafe(
block.getIcon(side, meta)
)
} catch {
case e: Exception =>
}
return MicroblockProxy.renderBlocks.getIconSafe(null)
} }
def createAndRegister(block:Block, meta:Int = 0):Unit = createAndRegister(block, Seq(meta)) val iblock = Block.getBlockFromName(
def createAndRegister(block:Block, meta:Seq[Int]):Unit = createAndRegister(block, meta, materialKey(block), oldKey(block)) blockKey
def createAndRegister(block:Block, meta:Seq[Int], oldName:String):Unit = createAndRegister(block, 0, materialKey(block), oldName) ) // reacquire block instance incase a mod replcaed it
icont = new MultiIconTransformation(
Array.tabulate(6)(side => safeIcon(iblock, side)): _*
)
}
def createAndRegister(block:Block, meta:Seq[Int], name:String, oldName:String):Unit = def renderMicroFace(pos: Vector3, pass: Int, bounds: Cuboid6) {
meta.foreach(m => createAndRegister(block, m, name, oldName)) MaterialRenderHelper
.start(pos, pass, icont)
.blockColour(getColour(pass))
.lighting()
.blockAndMeta(block, meta)
.render()
}
def getColour(pass: Int) = {
if (pass == -1)
block.getBlockColor << 8 | 0xff
else {
val state = CCRenderState.instance
val pos = state.lightMatrix.pos
block.colorMultiplier(
state.lightMatrix.access,
pos.x,
pos.y,
pos.z
) << 8 | 0xff
}
}
override def canRenderInPass(pass: Int) = block.canRenderInPass(pass)
@SideOnly(Side.CLIENT)
def getBreakingIcon(side: Int) = block.getIcon(side, meta)
def getItem = new ItemStack(block, 1, meta)
def getLocalizedName = getItem.getDisplayName
def getStrength(player: EntityPlayer) = {
var hardness = 30f
try {
hardness = block.getBlockHardness(null, 0, 0, 0)
} catch {
case e: Exception =>
}
player.getBreakSpeed(block, false, meta % 16, 0, -1, 0) / hardness
}
def isTransparent = !block.isOpaqueCube
def getLightValue = block.getLightValue
def toolClasses = Seq("axe", "pickaxe", "shovel")
// meta > 15 will throw ArrayIndexOutOfBoundsException
def getCutterStrength = block.getHarvestLevel(meta % 16)
def getSound = block.stepSound
def explosionResistance(entity: Entity): Float =
block.getExplosionResistance(entity)
}
/** Utility functions for cleaner registry code
*/
object BlockMicroMaterial {
def oldKey(block: Block) = block.getUnlocalizedName
def materialKey(block: Block) = Block.blockRegistry.getNameForObject(block)
def materialKey(name: String, meta: Int) =
name + (if (meta > 0) "_" + meta else "")
def materialKey(block: Block, meta: Int): String =
materialKey(materialKey(block), meta)
def createAndRegister(block: Block, meta: Int, name: String) =
MicroMaterialRegistry.registerMaterial(
new BlockMicroMaterial(block, meta),
materialKey(name, meta)
)
def createAndRegister(
block: Block,
meta: Int,
name: String,
oldName: String
) {
MicroMaterialRegistry.remapName(
materialKey(oldName, meta),
materialKey(name, meta)
)
createAndRegister(block, meta, name)
}
def createAndRegister(block: Block, meta: Int = 0): Unit =
createAndRegister(block, Seq(meta))
def createAndRegister(block: Block, meta: Seq[Int]): Unit =
createAndRegister(block, meta, materialKey(block), oldKey(block))
def createAndRegister(block: Block, meta: Seq[Int], oldName: String): Unit =
createAndRegister(block, 0, materialKey(block), oldName)
def createAndRegister(
block: Block,
meta: Seq[Int],
name: String,
oldName: String
): Unit =
meta.foreach(m => createAndRegister(block, m, name, oldName))
} }
@@ -16,133 +16,158 @@ import BlockMicroMaterial.materialKey
import java.lang.{Iterable => JIterable} import java.lang.{Iterable => JIterable}
import scala.collection.JavaConversions._ import scala.collection.JavaConversions._
object ConfigContent object ConfigContent {
{ private val nameMap = MMap[String, Seq[Int]]()
private val nameMap = MMap[String, Seq[Int]]()
def parse(cfgDir: File) { def parse(cfgDir: File) {
val cfgFile = new File(cfgDir, "microblocks.cfg") val cfgFile = new File(cfgDir, "microblocks.cfg")
try {
if (!cfgFile.exists())
generateDefault(cfgFile)
else
loadLines(cfgFile)
} catch {
case e: IOException => logger.error("Error parsing config", e)
}
}
def generateDefault(cfgFile: File) {
val writer = new PrintWriter(cfgFile)
writer.println(
"#Configuration file for adding microblock materials for aesthetic blocks added by mods"
)
writer.println("#Each line needs to be of the form <name>:<meta>")
writer.println(
"#<name> is the unlocalised name or registry key of the block/item enclosed in quotes. NEI can help you find these"
)
writer.println(
"#<meta> may be ommitted, in which case it defaults to 0, otherwise it can be a number, a comma separated list of numbers, or a dash separated range"
)
writer.println(
"#Ex. \"dirt\" \"minecraft:planks\":3 \"iron_ore\":1,2,3,5 \"ThermalFoundation:Storage\":0-15"
)
writer.close()
}
def loadLine(line: String) {
if (line.startsWith("#") || line.length < 3)
return
if (line.charAt(0) != '\"')
throw new IllegalArgumentException("Line must begin with a quote")
val q2 = line.indexOf('\"', 1)
if (q2 < 0)
throw new IllegalArgumentException("Unmatched quotes")
var name = line.substring(1, q2)
if (!name.contains('.') && !name.contains(':'))
name = "minecraft:" + name
var meta = Seq(0)
if (line.length > q2 + 1) {
if (line.charAt(q2 + 1) != ':')
throw new IllegalArgumentException(
"Name must be followed by a colon separator"
)
meta = line.substring(q2 + 2).split(",").flatMap { s =>
if (s.contains("-")) {
val split2 = s.split("-")
if (split2.length != 2)
throw new IllegalArgumentException("Invalid - separated range")
split2(0).toInt to split2(1).toInt
} else {
Seq(s.toInt)
}
}
}
nameMap.put(name, meta)
}
def loadLines(cfgFile: File) {
val reader = new BufferedReader(new FileReader(cfgFile))
var s: String = null
do {
s = reader.readLine
if (s != null) {
try { try {
if (!cfgFile.exists()) loadLine(s)
generateDefault(cfgFile) } catch {
else case e: Exception =>
loadLines(cfgFile) logger.error("Invalid line in microblocks.cfg: " + s)
logger.error(e.getMessage)
} }
catch { }
case e: IOException => logger.error("Error parsing config", e) } while (s != null)
reader.close()
}
def load() {
for (block <- Block.blockRegistry.asInstanceOf[JIterable[Block]]) {
val metas = Seq(
block.getUnlocalizedName,
Block.blockRegistry.getNameForObject(block)
).flatMap(nameMap.remove).flatten
metas.foreach { m =>
try {
createAndRegister(block, m)
} catch {
case e: IllegalStateException =>
logger.error(
"Unable to register micro material: " +
materialKey(block, m) + "\n\t" + e.getMessage
)
case e: Exception =>
logger.error(
"Unable to register micro material: " + materialKey(block, m),
e
)
} }
}
} }
def generateDefault(cfgFile: File) { nameMap.foreach(e =>
val writer = new PrintWriter(cfgFile) logger.warn(
writer.println("#Configuration file for adding microblock materials for aesthetic blocks added by mods") "Unable to add micro material for block with unlocalised name " + e._1 + " as it doesn't exist"
writer.println("#Each line needs to be of the form <name>:<meta>") )
writer.println("#<name> is the unlocalised name or registry key of the block/item enclosed in quotes. NEI can help you find these") )
writer.println("#<meta> may be ommitted, in which case it defaults to 0, otherwise it can be a number, a comma separated list of numbers, or a dash separated range") }
writer.println("#Ex. \"dirt\" \"minecraft:planks\":3 \"iron_ore\":1,2,3,5 \"ThermalFoundation:Storage\":0-15")
writer.close()
}
def loadLine(line: String) { def handleIMC(messages: Seq[IMCMessage]) {
if (line.startsWith("#") || line.length < 3) messages.filter(_.key == "microMaterial").foreach { msg =>
return def error(s: String) {
logger.error(
"Invalid microblock IMC message from " + msg.getSender + ": " + s
)
}
if(line.charAt(0) != '\"') if (msg.getMessageType != classOf[ItemStack])
throw new IllegalArgumentException("Line must begin with a quote") error("value is not an instanceof ItemStack")
val q2 = line.indexOf('\"', 1) else {
if(q2 < 0) val stack = msg.getItemStackValue
throw new IllegalArgumentException("Unmatched quotes") if (!Block.blockRegistry.containsId(Item.getIdFromItem(stack.getItem)))
error("Invalid Block: " + stack.getItem)
var name = line.substring(1, q2) else if (stack.getItemDamage < 0 || stack.getItemDamage >= 16)
if(!name.contains('.') && !name.contains(':')) error("Invalid metadata: " + stack.getItemDamage)
name = "minecraft:"+name else {
try {
var meta = Seq(0) createAndRegister(
if(line.length > q2+1) { Block.getBlockFromItem(stack.getItem),
if(line.charAt(q2+1) != ':') stack.getItemDamage
throw new IllegalArgumentException("Name must be followed by a colon separator") )
} catch {
meta = line.substring(q2+2).split(",").flatMap{s => case e: IllegalStateException =>
if (s.contains("-")) { error(
val split2 = s.split("-") "Unable to register micro material: " +
if (split2.length != 2) materialKey(
throw new IllegalArgumentException("Invalid - separated range") Block.getBlockFromItem(stack.getItem),
split2(0).toInt to split2(1).toInt stack.getItemDamage
} ) + "\n\t" + e.getMessage
else { )
Seq(s.toInt) }
}
}
}
nameMap.put(name, meta)
}
def loadLines(cfgFile: File) {
val reader = new BufferedReader(new FileReader(cfgFile))
var s: String = null
do {
s = reader.readLine
if (s != null) {
try {
loadLine(s)
}
catch {
case e: Exception =>
logger.error("Invalid line in microblocks.cfg: " + s)
logger.error(e.getMessage)
}
}
}
while (s != null)
reader.close()
}
def load() {
for(block <- Block.blockRegistry.asInstanceOf[JIterable[Block]]) {
val metas = Seq(block.getUnlocalizedName, Block.blockRegistry.getNameForObject(block)).flatMap(nameMap.remove).flatten
metas.foreach{m =>
try {
createAndRegister(block, m)
}
catch {
case e: IllegalStateException => logger.error("Unable to register micro material: " +
materialKey(block, m) + "\n\t" + e.getMessage)
case e: Exception =>
logger.error("Unable to register micro material: " + materialKey(block, m), e)
}
}
}
nameMap.foreach(e => logger.warn("Unable to add micro material for block with unlocalised name " + e._1 + " as it doesn't exist"))
}
def handleIMC(messages: Seq[IMCMessage]) {
messages.filter(_.key == "microMaterial").foreach{msg =>
def error(s: String) {
logger.error("Invalid microblock IMC message from " + msg.getSender + ": " + s)
}
if (msg.getMessageType != classOf[ItemStack])
error("value is not an instanceof ItemStack")
else {
val stack = msg.getItemStackValue
if (!Block.blockRegistry.containsId(Item.getIdFromItem(stack.getItem)))
error("Invalid Block: " + stack.getItem)
else if (stack.getItemDamage < 0 || stack.getItemDamage >= 16)
error("Invalid metadata: " + stack.getItemDamage)
else {
try {
createAndRegister(Block.getBlockFromItem(stack.getItem), stack.getItemDamage)
}
catch {
case e: IllegalStateException => error("Unable to register micro material: " +
materialKey(Block.getBlockFromItem(stack.getItem), stack.getItemDamage) + "\n\t" + e.getMessage)
}
}
}
} }
}
} }
}
} }
@@ -5,52 +5,48 @@ import codechicken.lib.vec.Scale
import codechicken.lib.vec.Vector3 import codechicken.lib.vec.Vector3
import Vector3._ import Vector3._
object CornerPlacement extends PlacementProperties object CornerPlacement extends PlacementProperties {
{ def microClass = CornerMicroClass
def microClass = CornerMicroClass
def placementGrid = CornerPlacementGrid def placementGrid = CornerPlacementGrid
def opposite(slot:Int, side:Int) = ((slot-7)^(1<<(side>>1)))+7 def opposite(slot: Int, side: Int) = ((slot - 7) ^ (1 << (side >> 1))) + 7
} }
object CornerMicroClass extends CommonMicroClass object CornerMicroClass extends CommonMicroClass {
{ var aBounds: Array[Cuboid6] = new Array(256)
var aBounds:Array[Cuboid6] = new Array(256)
for(s <- 0 until 8) for (s <- 0 until 8) {
{ val rx = if ((s & 4) != 0) -1 else 1
val rx = if((s&4) != 0) -1 else 1 val ry = if ((s & 1) != 0) -1 else 1
val ry = if((s&1) != 0) -1 else 1 val rz = if ((s & 2) != 0) -1 else 1
val rz = if((s&2) != 0) -1 else 1 val transform = new Scale(new Vector3(rx, ry, rz)).at(center)
val transform = new Scale(new Vector3(rx, ry, rz)).at(center)
for(t <- 1 until 8) for (t <- 1 until 8) {
{ val d = t / 8d
val d = t/8D aBounds(t << 4 | s) = new Cuboid6(0, 0, 0, d, d, d).apply(transform)
aBounds(t<<4|s) = new Cuboid6(0, 0, 0, d, d, d).apply(transform)
}
} }
}
def getName = "mcr_cnr" def getName = "mcr_cnr"
def baseTrait = classOf[CornerMicroblock] def baseTrait = classOf[CornerMicroblock]
def clientTrait = classOf[CommonMicroblockClient] def clientTrait = classOf[CommonMicroblockClient]
override def itemSlot = 7 override def itemSlot = 7
def placementProperties = CornerPlacement def placementProperties = CornerPlacement
def getResistanceFactor = 1 def getResistanceFactor = 1
} }
trait CornerMicroblock extends CommonMicroblock trait CornerMicroblock extends CommonMicroblock {
{ override def setShape(size: Int, slot: Int) = shape =
override def setShape(size: Int, slot: Int) = shape = (size<<4|(slot-7)).toByte (size << 4 | (slot - 7)).toByte
def microClass = CornerMicroClass def microClass = CornerMicroClass
def getBounds = CornerMicroClass.aBounds(shape) def getBounds = CornerMicroClass.aBounds(shape)
override def getSlot = getShape+7 override def getSlot = getShape + 7
} }
@@ -4,57 +4,57 @@ import net.minecraft.init.Blocks._
import BlockMicroMaterial._ import BlockMicroMaterial._
import MicroMaterialRegistry._ import MicroMaterialRegistry._
object DefaultContent object DefaultContent {
{ def load() {
def load() FaceMicroClass.register(0)
{ HollowMicroClass.register(1)
FaceMicroClass.register(0) CornerMicroClass.register(2)
HollowMicroClass.register(1) EdgeMicroClass.register(3)
CornerMicroClass.register(2) PostMicroClass.register()
EdgeMicroClass.register(3)
PostMicroClass.register()
createAndRegister(stone) createAndRegister(stone)
createAndRegister(dirt, 0 to 2) createAndRegister(dirt, 0 to 2)
createAndRegister(cobblestone) createAndRegister(cobblestone)
createAndRegister(planks, 0 to 5) createAndRegister(planks, 0 to 5)
createAndRegister(log, 0 to 3) createAndRegister(log, 0 to 3)
createAndRegister(log2, 0 to 1, "tile.log2") createAndRegister(log2, 0 to 1, "tile.log2")
createAndRegister(leaves, 0 to 3) createAndRegister(leaves, 0 to 3)
createAndRegister(leaves2, 0 to 1, "tile.leaves2") createAndRegister(leaves2, 0 to 1, "tile.leaves2")
createAndRegister(sponge) createAndRegister(sponge)
createAndRegister(glass) createAndRegister(glass)
createAndRegister(lapis_block) createAndRegister(lapis_block)
createAndRegister(sandstone, 0 to 2) createAndRegister(sandstone, 0 to 2)
createAndRegister(wool, 0 to 15) createAndRegister(wool, 0 to 15)
createAndRegister(gold_block) createAndRegister(gold_block)
createAndRegister(iron_block) createAndRegister(iron_block)
createAndRegister(brick_block) createAndRegister(brick_block)
createAndRegister(bookshelf) createAndRegister(bookshelf)
createAndRegister(mossy_cobblestone) createAndRegister(mossy_cobblestone)
createAndRegister(obsidian) createAndRegister(obsidian)
createAndRegister(diamond_block) createAndRegister(diamond_block)
createAndRegister(ice) createAndRegister(ice)
createAndRegister(snow) createAndRegister(snow)
createAndRegister(clay) createAndRegister(clay)
createAndRegister(netherrack) createAndRegister(netherrack)
createAndRegister(soul_sand) createAndRegister(soul_sand)
createAndRegister(glowstone) createAndRegister(glowstone)
createAndRegister(stonebrick, 0 to 3) createAndRegister(stonebrick, 0 to 3)
createAndRegister(nether_brick) createAndRegister(nether_brick)
createAndRegister(end_stone) createAndRegister(end_stone)
createAndRegister(emerald_block) createAndRegister(emerald_block)
createAndRegister(redstone_block) createAndRegister(redstone_block)
createAndRegister(quartz_block) createAndRegister(quartz_block)
createAndRegister(stained_hardened_clay, 0 to 15) createAndRegister(stained_hardened_clay, 0 to 15)
createAndRegister(hardened_clay) createAndRegister(hardened_clay)
createAndRegister(coal_block) createAndRegister(coal_block)
createAndRegister(packed_ice) createAndRegister(packed_ice)
createAndRegister(stained_glass, 0 to 15) createAndRegister(stained_glass, 0 to 15)
MicroMaterialRegistry.remapName(oldKey(grass), materialKey(grass)) MicroMaterialRegistry.remapName(oldKey(grass), materialKey(grass))
registerMaterial(new GrassMicroMaterial, materialKey(grass)) registerMaterial(new GrassMicroMaterial, materialKey(grass))
MicroMaterialRegistry.remapName(oldKey(mycelium), materialKey(mycelium)) MicroMaterialRegistry.remapName(oldKey(mycelium), materialKey(mycelium))
registerMaterial(new TopMicroMaterial(mycelium), materialKey(mycelium)) registerMaterial(new TopMicroMaterial(mycelium), materialKey(mycelium))
}
registerMaterial(MissingMicroMaterial, MissingMicroMaterial.key)
}
} }
@@ -20,217 +20,205 @@ import scala.collection.JavaConversions._
import codechicken.lib.data.MCDataInput import codechicken.lib.data.MCDataInput
import codechicken.lib.lighting.LightMatrix import codechicken.lib.lighting.LightMatrix
object EdgePlacement extends PlacementProperties object EdgePlacement extends PlacementProperties {
{ import codechicken.multipart.PartMap._
import codechicken.multipart.PartMap._
def microClass = EdgeMicroClass def microClass = EdgeMicroClass
def placementGrid = EdgePlacementGrid def placementGrid = EdgePlacementGrid
def opposite(slot:Int, side:Int):Int = def opposite(slot: Int, side: Int): Int = {
{ if (slot < 0) // custom placement
if(slot < 0)//custom placement return slot
return slot val e = slot - 15
val e = slot-15 return 15 + packEdgeBits(e, unpackEdgeBits(e) ^ (1 << (side >> 1)))
return 15+ packEdgeBits(e, unpackEdgeBits(e)^(1<<(side>>1))) }
}
override def customPlacement(pmt:MicroblockPlacement):ExecutablePlacement = override def customPlacement(
{ pmt: MicroblockPlacement
if(pmt.size%2 == 1) return null ): ExecutablePlacement = {
if (pmt.size % 2 == 1) return null
val part = PostMicroClass.create(pmt.world.isRemote, pmt.material) val part = PostMicroClass.create(pmt.world.isRemote, pmt.material)
part.setShape(pmt.size, pmt.hit.sideHit>>1) part.setShape(pmt.size, pmt.hit.sideHit >> 1)
if(pmt.doExpand) if (pmt.doExpand) {
{ val hpart = pmt.htile.partList(ExtendedMOP.getData[(Int, _)](pmt.hit)._1)
val hpart = pmt.htile.partList(ExtendedMOP.getData[(Int, _)](pmt.hit)._1) if (hpart.getType == PostMicroClass.getName) {
if(hpart.getType == PostMicroClass.getName) val mpart = hpart.asInstanceOf[Microblock]
{ if (mpart.material == pmt.material && mpart.getSize + pmt.size < 8) {
val mpart = hpart.asInstanceOf[Microblock] part.shape = ((mpart.getSize + pmt.size) << 4 | mpart.getShape).toByte
if(mpart.material == pmt.material && mpart.getSize + pmt.size < 8) return pmt.expand(mpart, part)
{
part.shape = ((mpart.getSize+pmt.size)<<4|mpart.getShape).toByte
return pmt.expand(mpart, part)
}
}
} }
}
if(pmt.slot >= 0)
return null
if(pmt.internal && !pmt.oppMod)
return pmt.internalPlacement(pmt.htile.asInstanceOf[TileMultipart], part)
return pmt.externalPlacement(part)
} }
if (pmt.slot >= 0)
return null
if (pmt.internal && !pmt.oppMod)
return pmt.internalPlacement(pmt.htile.asInstanceOf[TileMultipart], part)
return pmt.externalPlacement(part)
}
} }
object EdgeMicroClass extends CommonMicroClass object EdgeMicroClass extends CommonMicroClass {
{ var aBounds: Array[Cuboid6] = new Array(256)
var aBounds:Array[Cuboid6] = new Array(256)
for(s <- 0 until 12) for (s <- 0 until 12) {
{ val rx = if ((s & 2) != 0) -1 else 1
val rx = if((s&2) != 0) -1 else 1 val rz = if ((s & 1) != 0) -1 else 1
val rz = if((s&1) != 0) -1 else 1 val transform = new TransformationList(
val transform = new TransformationList(new Scale(new Vector3(rx, 1, rz)), AxisCycle.cycles(s>>2)).at(center) new Scale(new Vector3(rx, 1, rz)),
AxisCycle.cycles(s >> 2)
).at(center)
for(t <- 1 until 8) for (t <- 1 until 8) {
{ val d = t / 8d
val d = t/8D aBounds(t << 4 | s) = new Cuboid6(0, 0, 0, d, 1, d).apply(transform)
aBounds(t<<4|s) = new Cuboid6(0, 0, 0, d, 1, d).apply(transform)
}
} }
}
override def itemSlot = 15 override def itemSlot = 15
def getName = "mcr_edge" def getName = "mcr_edge"
def baseTrait = classOf[EdgeMicroblock] def baseTrait = classOf[EdgeMicroblock]
def clientTrait = classOf[CommonMicroblockClient] def clientTrait = classOf[CommonMicroblockClient]
def placementProperties = EdgePlacement def placementProperties = EdgePlacement
def getResistanceFactor = 0.5F def getResistanceFactor = 0.5f
} }
trait EdgeMicroblock extends CommonMicroblock with TEdgePart trait EdgeMicroblock extends CommonMicroblock with TEdgePart {
{ override def setShape(size: Int, slot: Int) = shape =
override def setShape(size: Int, slot: Int) = shape = (size<<4|(slot-15)).toByte (size << 4 | (slot - 15)).toByte
def microClass = EdgeMicroClass def microClass = EdgeMicroClass
def getBounds = EdgeMicroClass.aBounds(shape) def getBounds = EdgeMicroClass.aBounds(shape)
override def getSlot = getShape+15 override def getSlot = getShape + 15
} }
object PostMicroClass extends MicroblockClass object PostMicroClass extends MicroblockClass {
{ var aBounds: Array[Cuboid6] = new Array(256)
var aBounds:Array[Cuboid6] = new Array(256)
for(s <- 0 until 3) for (s <- 0 until 3) {
{ val transform = sideRotations(s << 1).at(center)
val transform = sideRotations(s<<1).at(center) for (t <- 2 until 8 by 2) {
for(t <- 2 until 8 by 2) val d1 = 0.5 - t / 16d
{ val d2 = 0.5 + t / 16d
val d1 = 0.5-t/16D aBounds(t << 4 | s) = new Cuboid6(d1, 0, d1, d2, 1, d2).apply(transform)
val d2 = 0.5+t/16D
aBounds(t<<4|s) = new Cuboid6(d1, 0, d1, d2, 1, d2).apply(transform)
}
} }
}
def getName = "mcr_post" def getName = "mcr_post"
def baseTrait = classOf[PostMicroblock] def baseTrait = classOf[PostMicroblock]
def clientTrait = classOf[PostMicroblockClient] def clientTrait = classOf[PostMicroblockClient]
def getResistanceFactor = 0.5F def getResistanceFactor = 0.5f
} }
trait PostMicroblockClient extends PostMicroblock with MicroblockClient trait PostMicroblockClient extends PostMicroblock with MicroblockClient {
{ var renderBounds1: Cuboid6 = _
var renderBounds1:Cuboid6 = _ var renderBounds2: Cuboid6 = _
var renderBounds2:Cuboid6 = _
override def render(pos:Vector3, pass:Int) override def render(pos: Vector3, pass: Int) {
{ val mat = getIMaterial
val mat = getIMaterial if (pass == -1)
if(pass == -1) MicroblockRender.renderCuboid(pos, mat, pass, getBounds, 0)
MicroblockRender.renderCuboid(pos, mat, pass, getBounds, 0) else {
else { MicroblockRender.renderCuboid(pos, mat, pass, renderBounds1, 0)
MicroblockRender.renderCuboid(pos, mat, pass, renderBounds1, 0) if (renderBounds2 != null)
if (renderBounds2 != null) MicroblockRender.renderCuboid(pos, mat, pass, renderBounds2, 0)
MicroblockRender.renderCuboid(pos, mat, pass, renderBounds2, 0)
}
} }
}
override def onPartChanged(part:TMultiPart) override def onPartChanged(part: TMultiPart) {
{ recalcBounds()
recalcBounds() }
override def onAdded() {
super.onAdded()
recalcBounds()
}
override def read(packet: MCDataInput) {
super.read(packet)
recalcBounds()
}
def recalcBounds() {
renderBounds1 = getBounds.copy
renderBounds2 = null
shrinkFace(getShape << 1)
shrinkFace(getShape << 1 | 1)
tile.partList.foreach(p =>
if (p.isInstanceOf[PostMicroblock] && p != this)
shrinkPost(p.asInstanceOf[PostMicroblock])
)
}
def shrinkFace(fside: Int) {
val part = tile.partMap(fside)
if (part != null && part.getType.equals("mcr_face"))
MicroOcclusion.shrink(
renderBounds1,
part.asInstanceOf[CommonMicroblock].getBounds,
fside
)
}
def shrinkPost(post: PostMicroblock) {
if (post == this)
return
if (thisShrinks(post)) {
if (renderBounds2 == null)
renderBounds2 = getBounds.copy
MicroOcclusion.shrink(renderBounds1, post.getBounds, getShape << 1 | 1)
MicroOcclusion.shrink(renderBounds2, post.getBounds, getShape << 1)
} }
}
override def onAdded() def thisShrinks(other: PostMicroblock): Boolean = {
{ if (getSize != other.getSize) return getSize < other.getSize
super.onAdded() if (isTransparent != other.isTransparent) return isTransparent
recalcBounds() return getShape > other.getShape
} }
override def read(packet:MCDataInput)
{
super.read(packet)
recalcBounds()
}
def recalcBounds()
{
renderBounds1 = getBounds.copy
renderBounds2 = null
shrinkFace(getShape<<1)
shrinkFace(getShape<<1|1)
tile.partList.foreach(p =>
if(p.isInstanceOf[PostMicroblock] && p != this)
shrinkPost(p.asInstanceOf[PostMicroblock])
)
}
def shrinkFace(fside:Int)
{
val part = tile.partMap(fside)
if(part != null && part.getType.equals("mcr_face"))
MicroOcclusion.shrink(renderBounds1, part.asInstanceOf[CommonMicroblock].getBounds, fside)
}
def shrinkPost(post:PostMicroblock)
{
if(post == this)
return
if(thisShrinks(post))
{
if(renderBounds2 == null)
renderBounds2 = getBounds.copy
MicroOcclusion.shrink(renderBounds1, post.getBounds, getShape<<1|1)
MicroOcclusion.shrink(renderBounds2, post.getBounds, getShape<<1)
}
}
def thisShrinks(other:PostMicroblock):Boolean =
{
if(getSize != other.getSize) return getSize < other.getSize
if(isTransparent != other.isTransparent) return isTransparent
return getShape > other.getShape
}
} }
trait PostMicroblock extends Microblock with JPartialOcclusion with TNormalOcclusion trait PostMicroblock
{ extends Microblock
def microClass = PostMicroClass with JPartialOcclusion
with TNormalOcclusion {
def microClass = PostMicroClass
def getBounds = PostMicroClass.aBounds(shape) def getBounds = PostMicroClass.aBounds(shape)
def getOcclusionBoxes = Seq(getBounds) def getOcclusionBoxes = Seq(getBounds)
def getPartialOcclusionBoxes = getOcclusionBoxes def getPartialOcclusionBoxes = getOcclusionBoxes
override def itemClassID = EdgeMicroClass.getClassId override def itemClassID = EdgeMicroClass.getClassId
override def occlusionTest(npart:TMultiPart): Boolean = override def occlusionTest(npart: TMultiPart): Boolean = {
{ if (npart.isInstanceOf[PostMicroblock])
if(npart.isInstanceOf[PostMicroblock]) return npart.asInstanceOf[PostMicroblock].getShape != getShape
return npart.asInstanceOf[PostMicroblock].getShape != getShape
if(npart.getType.equals("mcr_face")) if (npart.getType.equals("mcr_face"))
if(npart.asInstanceOf[CommonMicroblock].getSlot>>1 == getShape) if (npart.asInstanceOf[CommonMicroblock].getSlot >> 1 == getShape)
return true return true
return super.occlusionTest(npart) return super.occlusionTest(npart)
} }
def getResistanceFactor = PostMicroClass.getResistanceFactor def getResistanceFactor = PostMicroClass.getResistanceFactor
override def canPlaceTorchOnTop = getShape == 0 override def canPlaceTorchOnTop = getShape == 0
} }
@@ -7,67 +7,79 @@ import codechicken.lib.vec.Rotation
import Rotation._ import Rotation._
import Vector3._ import Vector3._
object FacePlacement extends PlacementProperties object FacePlacement extends PlacementProperties {
{ def microClass = FaceMicroClass
def microClass = FaceMicroClass
def placementGrid = FacePlacementGrid def placementGrid = FacePlacementGrid
def opposite(slot:Int, side:Int) = slot^1 def opposite(slot: Int, side: Int) = slot ^ 1
override def expand(slot:Int, side:Int) = sneakOpposite(slot, side) override def expand(slot: Int, side: Int) = sneakOpposite(slot, side)
override def sneakOpposite(slot:Int, side:Int) = slot == (side^1) override def sneakOpposite(slot: Int, side: Int) = slot == (side ^ 1)
} }
class FaceMicroClass class FaceMicroClass
object FaceMicroClass extends CommonMicroClass object FaceMicroClass extends CommonMicroClass {
{ var aBounds: Array[Cuboid6] = new Array(256)
var aBounds:Array[Cuboid6] = new Array(256)
for(s <- 0 until 6) for (s <- 0 until 6) {
{ val transform = sideRotations(s).at(center)
val transform = sideRotations(s).at(center) for (t <- 1 until 8) {
for(t <- 1 until 8) val d = t / 8d
{ aBounds(t << 4 | s) = new Cuboid6(0, 0, 0, 1, d, 1).apply(transform)
val d = t/8D
aBounds(t<<4|s) = new Cuboid6(0, 0, 0, 1, d, 1).apply(transform)
}
} }
}
def getName = "mcr_face" def getName = "mcr_face"
def itemSlot = 3 def itemSlot = 3
def baseTrait = classOf[FaceMicroblock] def baseTrait = classOf[FaceMicroblock]
def clientTrait = classOf[FaceMicroblockClient] def clientTrait = classOf[FaceMicroblockClient]
def placementProperties = FacePlacement def placementProperties = FacePlacement
def getResistanceFactor = 1 def getResistanceFactor = 1
} }
trait FaceMicroblockClient extends CommonMicroblockClient trait FaceMicroblockClient extends CommonMicroblockClient {
{ override def render(pos: Vector3, pass: Int) {
override def render(pos:Vector3, pass:Int) { if (pass < 0)
if(pass < 0) MicroblockRender.renderCuboid(pos, getIMaterial, pass, getBounds, 0)
MicroblockRender.renderCuboid(pos, getIMaterial, pass, getBounds, 0) else if (isTransparent)
else if(isTransparent) MicroblockRender.renderCuboid(
MicroblockRender.renderCuboid(pos, getIMaterial, pass, renderBounds, renderMask) pos,
else { getIMaterial,
val mat = getIMaterial pass,
MicroblockRender.renderCuboid(pos, mat, pass, renderBounds, renderMask | 1<<getSlot) renderBounds,
MicroblockRender.renderCuboid(pos, mat, pass, Cuboid6.full, ~(1<<getSlot)) renderMask
} )
else {
val mat = getIMaterial
MicroblockRender.renderCuboid(
pos,
mat,
pass,
renderBounds,
renderMask | 1 << getSlot
)
MicroblockRender.renderCuboid(
pos,
mat,
pass,
Cuboid6.full,
~(1 << getSlot)
)
} }
}
} }
trait FaceMicroblock extends CommonMicroblock with TFacePart trait FaceMicroblock extends CommonMicroblock with TFacePart {
{ def microClass = FaceMicroClass
def microClass = FaceMicroClass
def getBounds = FaceMicroClass.aBounds(shape) def getBounds = FaceMicroClass.aBounds(shape)
override def solid(side:Int) = getIMaterial.isSolid override def solid(side: Int) = getIMaterial.isSolid
} }
@@ -2,47 +2,62 @@ package codechicken.microblock
import codechicken.lib.vec.{Cuboid6, Vector3} import codechicken.lib.vec.{Cuboid6, Vector3}
import net.minecraft.block.Block import net.minecraft.block.Block
import codechicken.lib.render.{ColourMultiplier, CCRenderState} import codechicken.lib.render.CCRenderState
import net.minecraft.block.BlockGrass import net.minecraft.block.BlockGrass
import net.minecraft.init.Blocks import net.minecraft.init.Blocks
import codechicken.lib.render.uv.{UVTranslation, IconTransformation} import codechicken.lib.render.uv.{UVTranslation, IconTransformation}
import codechicken.lib.render.BlockRenderer.BlockFace import codechicken.lib.render.BlockRenderer.BlockFace
class GrassMicroMaterial extends BlockMicroMaterial(Blocks.grass, 0) class GrassMicroMaterial extends BlockMicroMaterial(Blocks.grass, 0) {
{ var sideIconT: IconTransformation = _
var sideIconT:IconTransformation = _
override def loadIcons() override def loadIcons() {
{ super.loadIcons()
super.loadIcons() sideIconT = new IconTransformation(BlockGrass.getIconSideOverlay)
sideIconT = new IconTransformation(BlockGrass.getIconSideOverlay) }
}
override def renderMicroFace(pos:Vector3, pass:Int, bounds:Cuboid6) { override def renderMicroFace(pos: Vector3, pass: Int, bounds: Cuboid6) {
val face = CCRenderState.model.asInstanceOf[BlockFace] val face = CCRenderState.instance().model.asInstanceOf[BlockFace]
if(pass != -1) if (pass != -1)
face.computeLightCoords() face.computeLightCoords()
if(face.side == 1) if (face.side == 1)
MaterialRenderHelper.start(pos, pass, icont).blockColour(getColour(pass)).lighting().render() MaterialRenderHelper
else .start(pos, pass, icont)
MaterialRenderHelper.start(pos, pass, icont).lighting().render() .blockColour(getColour(pass))
.lighting()
.blockAndMeta(block, meta)
.render()
else
MaterialRenderHelper.start(pos, pass, icont).lighting().render()
if(face.side > 1) if (face.side > 1)
MaterialRenderHelper.start(pos, pass, new UVTranslation(0, bounds.max.y-1) ++ sideIconT) MaterialRenderHelper
.blockColour(getColour(pass)).lighting().render() .start(pos, pass, new UVTranslation(0, bounds.max.y - 1) ++ sideIconT)
} .blockColour(getColour(pass))
.lighting()
.blockAndMeta(block, meta)
.render()
}
} }
class TopMicroMaterial($block:Block, $meta:Int = 0) extends BlockMicroMaterial($block, $meta) class TopMicroMaterial($block: Block, $meta: Int = 0)
{ extends BlockMicroMaterial($block, $meta) {
override def renderMicroFace(pos:Vector3, pass:Int, bounds:Cuboid6) override def renderMicroFace(pos: Vector3, pass: Int, bounds: Cuboid6) {
{ val face = CCRenderState.instance().model.asInstanceOf[BlockFace]
val face = CCRenderState.model.asInstanceOf[BlockFace] if (face.side <= 1)
if(face.side <= 1) MaterialRenderHelper
MaterialRenderHelper.start(pos, pass, icont).blockColour(getColour(pass)).lighting().render() .start(pos, pass, icont)
else .blockColour(getColour(pass))
MaterialRenderHelper.start(pos, pass, new UVTranslation(0, bounds.max.y-1) ++ icont) .lighting()
.blockColour(getColour(pass)).lighting().render() .blockAndMeta(block, meta)
} .render()
else
MaterialRenderHelper
.start(pos, pass, new UVTranslation(0, bounds.max.y - 1) ++ icont)
.blockColour(getColour(pass))
.lighting()
.blockAndMeta(block, meta)
.render()
}
} }
@@ -14,228 +14,403 @@ import Vector3._
import codechicken.lib.raytracer.IndexedCuboid6 import codechicken.lib.raytracer.IndexedCuboid6
import org.lwjgl.opengl.GL11 import org.lwjgl.opengl.GL11
import codechicken.lib.render.uv.IconTransformation import codechicken.lib.render.uv.IconTransformation
import codechicken.lib.lighting.LightMatrix
object HollowPlacement extends PlacementProperties object HollowPlacement extends PlacementProperties {
{ object HollowPlacementGrid extends FaceEdgeGrid(3 / 8d)
object HollowPlacementGrid extends FaceEdgeGrid(3 / 8D)
def microClass = HollowMicroClass def microClass = HollowMicroClass
def placementGrid = HollowPlacementGrid def placementGrid = HollowPlacementGrid
def opposite(slot: Int, side: Int) = slot ^ 1 def opposite(slot: Int, side: Int) = slot ^ 1
override def expand(slot: Int, side: Int) = sneakOpposite(slot, side) override def expand(slot: Int, side: Int) = sneakOpposite(slot, side)
override def sneakOpposite(slot: Int, side: Int) = slot == (side ^ 1) override def sneakOpposite(slot: Int, side: Int) = slot == (side ^ 1)
} }
object HollowMicroClass extends CommonMicroClass object HollowMicroClass extends CommonMicroClass {
{ var pBoxes: Array[Seq[Cuboid6]] = new Array(256)
var pBoxes: Array[Seq[Cuboid6]] = new Array(256) var occBounds: Array[Cuboid6] = new Array(256)
var occBounds: Array[Cuboid6] = new Array(256) for (s <- 0 until 6) {
for (s <- 0 until 6) { val transform = sideRotations(s).at(center)
val transform = sideRotations(s).at(center) for (t <- 1 until 8) {
for (t <- 1 until 8) { val d = t / 8d
val d = t / 8D val w1 = 1 / 8d
val w1 = 1 / 8D val w2 = 3 / 16d
val w2 = 3 / 16D pBoxes(t << 4 | s) = Seq(
pBoxes(t << 4 | s) = Seq( new Cuboid6(0, 0, 0, w1, d, 1),
new Cuboid6(0, 0, 0, w1, d, 1), new Cuboid6(1 - w1, 0, 0, 1, d, 1),
new Cuboid6(1 - w1, 0, 0, 1, d, 1), new Cuboid6(w1, 0, 0, 1 - w1, d, w1),
new Cuboid6(w1, 0, 0, 1 - w1, d, w1), new Cuboid6(w1, 0, 1 - w1, 1 - w1, d, 1)
new Cuboid6(w1, 0, 1 - w1, 1 - w1, d, 1)) )
.map(_.apply(transform)) .map(_.apply(transform))
occBounds(t << 4 | s) = new Cuboid6(1 / 8D, 0, 1 / 8D, 7 / 8D, d, 7 / 8D).apply(transform) occBounds(t << 4 | s) =
} new Cuboid6(1 / 8d, 0, 1 / 8d, 7 / 8d, d, 7 / 8d).apply(transform)
} }
}
def getName = "mcr_hllw" def getName = "mcr_hllw"
def baseTrait = classOf[HollowMicroblock] def baseTrait = classOf[HollowMicroblock]
def clientTrait = classOf[HollowMicroblockClient] def clientTrait = classOf[HollowMicroblockClient]
def itemSlot = 3 def itemSlot = 3
def placementProperties = HollowPlacement def placementProperties = HollowPlacement
def getResistanceFactor = 1 def getResistanceFactor = 1
} }
trait HollowMicroblockClient extends HollowMicroblock with CommonMicroblockClient trait HollowMicroblockClient
{ extends HollowMicroblock
renderMask |= 8 << 8 with CommonMicroblockClient {
renderMask |= 8 << 8
override def recalcBounds() { override def recalcBounds() {
super.recalcBounds() super.recalcBounds()
renderMask = renderMask & 0xFF | getHollowSize << 8 renderMask = renderMask & 0xff | getHollowSize << 8
}
override def drawBreaking(renderBlocks: RenderBlocks) {
val state = CCRenderState.instance
state.resetInstance()
state.setPipelineInstance(
new Translation(x, y, z),
new IconTransformation(renderBlocks.overrideBlockTexture)
)
renderHollow(
null,
0,
getBounds,
0,
false,
(
pos: Vector3,
mat: IMicroMaterial,
pass: Int,
c: Cuboid6,
sideMask: Int
) => BlockRenderer.renderCuboid(c, sideMask)
)
}
override def render(pos: Vector3, pass: Int) {
if (pass == -1)
renderHollow(
pos,
pass,
getBounds,
0,
false,
MicroblockRender.renderCuboid
)
else if (isTransparent)
renderHollow(
pos,
pass,
renderBounds,
renderMask,
false,
MicroblockRender.renderCuboid
)
else {
renderHollow(
pos,
pass,
renderBounds,
renderMask | 1 << getSlot,
false,
MicroblockRender.renderCuboid
)
renderHollow(
pos,
pass,
Cuboid6.full,
~(1 << getSlot),
true,
MicroblockRender.renderCuboid
)
} }
}
override def drawBreaking(renderBlocks: RenderBlocks) { def renderHollow(
CCRenderState.reset() pos: Vector3,
CCRenderState.setPipeline(new Translation(x, y, z), new IconTransformation(renderBlocks.overrideBlockTexture)) pass: Int,
renderHollow(null, 0, getBounds, 0, false, c: Cuboid6,
(pos: Vector3, mat: IMicroMaterial, pass: Int, c: Cuboid6, sideMask: Int) => sideMask: Int,
BlockRenderer.renderCuboid(c, sideMask)) face: Boolean,
f: (Vector3, IMicroMaterial, Int, Cuboid6, Int) => Unit
) {
val mat = getIMaterial
val size = renderMask >> 8
val d1 = 0.5 - size / 32d
val d2 = 0.5 + size / 32d
val x1 = c.min.x
val x2 = c.max.x
val y1 = c.min.y
val y2 = c.max.y
val z1 = c.min.z
val z2 = c.max.z
var iMask = 0
getSlot match {
case 0 | 1 =>
if (face)
iMask = 0x3c
f(
pos,
mat,
pass,
new Cuboid6(d1, y1, d2, d2, y2, z2),
0x3b | iMask
) // -z internal
f(
pos,
mat,
pass,
new Cuboid6(d1, y1, z1, d2, y2, d1),
0x37 | iMask
) // +z internal
f(
pos,
mat,
pass,
new Cuboid6(d2, y1, d1, x2, y2, d2),
sideMask & 0x23 | 0xc | iMask
) // -x internal -y+y+x external
f(
pos,
mat,
pass,
new Cuboid6(x1, y1, d1, d1, y2, d2),
sideMask & 0x13 | 0xc | iMask
) // +x internal -y+y-x external
f(
pos,
mat,
pass,
new Cuboid6(x1, y1, d2, x2, y2, z2),
sideMask & 0x3b | 4 | iMask
) // -y+y+z-x+x external
f(
pos,
mat,
pass,
new Cuboid6(x1, y1, z1, x2, y2, d1),
sideMask & 0x37 | 8 | iMask
) // -y+y-z-x+x external
case 2 | 3 =>
if (face)
iMask = 0x33
f(
pos,
mat,
pass,
new Cuboid6(d2, d1, z1, x2, d2, z2),
0x2f | iMask
) // -x internal
f(
pos,
mat,
pass,
new Cuboid6(x1, d1, z1, d1, d2, z2),
0x1f | iMask
) // +x internal
f(
pos,
mat,
pass,
new Cuboid6(d1, d2, z1, d2, y2, z2),
sideMask & 0xe | 0x30 | iMask
) // -y internal -z+z+y external
f(
pos,
mat,
pass,
new Cuboid6(d1, y1, z1, d2, d1, z2),
sideMask & 0xd | 0x30 | iMask
) // +y internal -z+z-y external
f(
pos,
mat,
pass,
new Cuboid6(d2, y1, z1, x2, y2, z2),
sideMask & 0x2f | 0x10 | iMask
) // -z+z+x-y+y external
f(
pos,
mat,
pass,
new Cuboid6(x1, y1, z1, d1, y2, z2),
sideMask & 0x1f | 0x20 | iMask
) // -z+z-x-y+y external
case 4 | 5 =>
if (face)
iMask = 0xf
f(
pos,
mat,
pass,
new Cuboid6(x1, d2, d1, x2, y2, d2),
0x3e | iMask
) // -y internal
f(
pos,
mat,
pass,
new Cuboid6(x1, y1, d1, x2, d1, d2),
0x3d | iMask
) // +y internal
f(
pos,
mat,
pass,
new Cuboid6(x1, d1, d2, x2, d2, z2),
sideMask & 0x38 | 3 | iMask
) // -z internal -x+x+z external
f(
pos,
mat,
pass,
new Cuboid6(x1, d1, z1, x2, d2, d1),
sideMask & 0x34 | 3 | iMask
) // +z internal -x+x-z external
f(
pos,
mat,
pass,
new Cuboid6(x1, d2, z1, x2, y2, z2),
sideMask & 0x3e | 1 | iMask
) // -x+x+y-z+z external
f(
pos,
mat,
pass,
new Cuboid6(x1, y1, z1, x2, d1, z2),
sideMask & 0x3d | 2 | iMask
) // -x+x-y-z+z external
} }
}
override def render(pos: Vector3, pass: Int) { override def drawHighlight(
if (pass == -1) hit: MovingObjectPosition,
renderHollow(pos, pass, getBounds, 0, false, MicroblockRender.renderCuboid) player: EntityPlayer,
else if (isTransparent) frame: Float
renderHollow(pos, pass, renderBounds, renderMask, false, MicroblockRender.renderCuboid) ): Boolean = {
else { val size = getHollowSize
renderHollow(pos, pass, renderBounds, renderMask | 1 << getSlot, false, MicroblockRender.renderCuboid) val d1 = 0.5 - size / 32d
renderHollow(pos, pass, Cuboid6.full, ~(1 << getSlot), true, MicroblockRender.renderCuboid) val d2 = 0.5 + size / 32d
} val t = (shape >> 4) / 8d
}
def renderHollow(pos: Vector3, pass: Int, c: Cuboid6, sideMask: Int, face: Boolean, import GL11._
f: (Vector3, IMicroMaterial, Int, Cuboid6, Int) => Unit) { glEnable(GL_BLEND)
val mat = getIMaterial glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
val size = renderMask >> 8 glDisable(GL_TEXTURE_2D)
val d1 = 0.5 - size / 32D glColor4f(0, 0, 0, 0.4f)
val d2 = 0.5 + size / 32D glLineWidth(2)
val x1 = c.min.x glDepthMask(false)
val x2 = c.max.x glPushMatrix()
val y1 = c.min.y RenderUtils.translateToWorldCoords(player, frame)
val y2 = c.max.y glTranslated(x, y, z)
val z1 = c.min.z sideRotations(shape & 0xf).at(center).glApply()
val z2 = c.max.z
var iMask = 0 RenderUtils.drawCuboidOutline(new Cuboid6(0, 0, 0, 1, t, 1).expand(0.001))
getSlot match { RenderUtils.drawCuboidOutline(
case 0 | 1 => new Cuboid6(d1, 0, d1, d2, t, d2).expand(-0.001)
if (face) )
iMask = 0x3C glPopMatrix()
f(pos, mat, pass, new Cuboid6(d1, y1, d2, d2, y2, z2), 0x3B | iMask) //-z internal glDepthMask(true)
f(pos, mat, pass, new Cuboid6(d1, y1, z1, d2, y2, d1), 0x37 | iMask) //+z internal glEnable(GL_TEXTURE_2D)
glDisable(GL_BLEND)
f(pos, mat, pass, new Cuboid6(d2, y1, d1, x2, y2, d2), sideMask & 0x23 | 0xC | iMask) //-x internal -y+y+x external return true
f(pos, mat, pass, new Cuboid6(x1, y1, d1, d1, y2, d2), sideMask & 0x13 | 0xC | iMask) //+x internal -y+y-x external }
f(pos, mat, pass, new Cuboid6(x1, y1, d2, x2, y2, z2), sideMask & 0x3B | 4 | iMask) //-y+y+z-x+x external
f(pos, mat, pass, new Cuboid6(x1, y1, z1, x2, y2, d1), sideMask & 0x37 | 8 | iMask) //-y+y-z-x+x external
case 2 | 3 =>
if (face)
iMask = 0x33
f(pos, mat, pass, new Cuboid6(d2, d1, z1, x2, d2, z2), 0x2F | iMask) //-x internal
f(pos, mat, pass, new Cuboid6(x1, d1, z1, d1, d2, z2), 0x1F | iMask) //+x internal
f(pos, mat, pass, new Cuboid6(d1, d2, z1, d2, y2, z2), sideMask & 0xE | 0x30 | iMask) //-y internal -z+z+y external
f(pos, mat, pass, new Cuboid6(d1, y1, z1, d2, d1, z2), sideMask & 0xD | 0x30 | iMask) //+y internal -z+z-y external
f(pos, mat, pass, new Cuboid6(d2, y1, z1, x2, y2, z2), sideMask & 0x2F | 0x10 | iMask) //-z+z+x-y+y external
f(pos, mat, pass, new Cuboid6(x1, y1, z1, d1, y2, z2), sideMask & 0x1F | 0x20 | iMask) //-z+z-x-y+y external
case 4 | 5 =>
if (face)
iMask = 0xF
f(pos, mat, pass, new Cuboid6(x1, d2, d1, x2, y2, d2), 0x3E | iMask) //-y internal
f(pos, mat, pass, new Cuboid6(x1, y1, d1, x2, d1, d2), 0x3D | iMask) //+y internal
f(pos, mat, pass, new Cuboid6(x1, d1, d2, x2, d2, z2), sideMask & 0x38 | 3 | iMask) //-z internal -x+x+z external
f(pos, mat, pass, new Cuboid6(x1, d1, z1, x2, d2, d1), sideMask & 0x34 | 3 | iMask) //+z internal -x+x-z external
f(pos, mat, pass, new Cuboid6(x1, d2, z1, x2, y2, z2), sideMask & 0x3E | 1 | iMask) //-x+x+y-z+z external
f(pos, mat, pass, new Cuboid6(x1, y1, z1, x2, d1, z2), sideMask & 0x3D | 2 | iMask) //-x+x-y-z+z external
}
}
override def drawHighlight(hit: MovingObjectPosition, player: EntityPlayer, frame: Float): Boolean = {
val size = getHollowSize
val d1 = 0.5 - size / 32D
val d2 = 0.5 + size / 32D
val t = (shape >> 4) / 8D
import GL11._
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glDisable(GL_TEXTURE_2D)
glColor4f(0, 0, 0, 0.4F)
glLineWidth(2)
glDepthMask(false)
glPushMatrix()
RenderUtils.translateToWorldCoords(player, frame)
glTranslated(x, y, z)
sideRotations(shape & 0xF).at(center).glApply()
RenderUtils.drawCuboidOutline(new Cuboid6(0, 0, 0, 1, t, 1).expand(0.001))
RenderUtils.drawCuboidOutline(new Cuboid6(d1, 0, d1, d2, t, d2).expand(-0.001))
glPopMatrix()
glDepthMask(true)
glEnable(GL_TEXTURE_2D)
glDisable(GL_BLEND)
return true
}
} }
trait HollowMicroblock extends CommonMicroblock with TFacePart with TNormalOcclusion trait HollowMicroblock
{ extends CommonMicroblock
def microClass = HollowMicroClass with TFacePart
with TNormalOcclusion {
def microClass = HollowMicroClass
def getBounds: Cuboid6 = FaceMicroClass.aBounds(shape) def getBounds: Cuboid6 = FaceMicroClass.aBounds(shape)
override def getPartialOcclusionBoxes = HollowMicroClass.pBoxes(shape) override def getPartialOcclusionBoxes = HollowMicroClass.pBoxes(shape)
def getHollowSize = tile match { def getHollowSize = tile match {
case null => 8 case null => 8
case _ => tile.partMap(6) match { case _ =>
case part: ISidedHollowConnect => part.getHollowSize(getSlot) tile.partMap(6) match {
case _ => 8 case part: ISidedHollowConnect => part.getHollowSize(getSlot)
} case _ => 8
}
}
def getOcclusionBoxes = {
val size = getHollowSize
val c = HollowMicroClass.occBounds(shape)
val d1 = 0.5 - size / 32d
val d2 = 0.5 + size / 32d
val x1 = c.min.x
val x2 = c.max.x
val y1 = c.min.y
val y2 = c.max.y
val z1 = c.min.z
val z2 = c.max.z
getSlot match {
case 0 | 1 =>
Seq(
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 | 3 =>
Seq(
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 | 5 =>
Seq(
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)
)
} }
}
def getOcclusionBoxes = { override def getCollisionBoxes = {
val size = getHollowSize val size = getHollowSize
val c = HollowMicroClass.occBounds(shape) val d1 = 0.5 - size / 32d
val d1 = 0.5 - size / 32D val d2 = 0.5 + size / 32d
val d2 = 0.5 + size / 32D val t = (shape >> 4) / 8d
val x1 = c.min.x
val x2 = c.max.x
val y1 = c.min.y
val y2 = c.max.y
val z1 = c.min.z
val z2 = c.max.z
getSlot match { val tr = sideRotations(shape & 0xf).at(center)
case 0 | 1 => Seq(
Seq(new Cuboid6(d2, y1, d1, x2, y2, d2), new Cuboid6(0, 0, 0, 1, t, d1),
new Cuboid6(x1, y1, d1, d1, y2, d2), new Cuboid6(0, 0, d2, 1, t, 1),
new Cuboid6(x1, y1, d2, x2, y2, z2), new Cuboid6(0, 0, d1, d1, t, d2),
new Cuboid6(x1, y1, z1, x2, y2, d1)) new Cuboid6(d2, 0, d1, 1, t, d2)
case 2 | 3 => )
Seq(new Cuboid6(d1, d2, z1, d2, y2, z2), .map(c => c.apply(tr))
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 | 5 =>
Seq(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))
}
}
override def getCollisionBoxes = { override def getSubParts =
val size = getHollowSize getCollisionBoxes.map(c => new IndexedCuboid6(0, c))
val d1 = 0.5 - size / 32D
val d2 = 0.5 + size / 32D
val t = (shape >> 4) / 8D
val tr = sideRotations(shape & 0xF).at(center) override def allowCompleteOcclusion = true
Seq(new Cuboid6(0, 0, 0, 1, t, d1),
new Cuboid6(0, 0, d2, 1, t, 1),
new Cuboid6(0, 0, d1, d1, t, d2),
new Cuboid6(d2, 0, d1, 1, t, d2))
.map(c => c.apply(tr))
}
override def getSubParts = getCollisionBoxes.map(c => new IndexedCuboid6(0, c)) override def solid(side: Int) = false
override def allowCompleteOcclusion = true override def redstoneConductionMap = 0x10
override def solid(side: Int) = false
override def redstoneConductionMap = 0x10
} }
@@ -3,20 +3,19 @@ package codechicken.microblock
import codechicken.lib.vec.Cuboid6 import codechicken.lib.vec.Cuboid6
import net.minecraft.world.World import net.minecraft.world.World
/** /** Wrapper class blocks/tiles/parts wanting to use the micro material system to
* Wrapper class blocks/tiles/parts wanting to use the micro material system to render part of their models. * render part of their models.
*/ */
trait IMicroMaterialRender { trait IMicroMaterialRender {
/**
* May be null for inventory rendering.
*/
def world:World
def x:Int
def y:Int
def z:Int
/** /** May be null for inventory rendering.
* Return the bounds of the part for texture mapping side decals like grass */
*/ def world: World
def getRenderBounds:Cuboid6 def x: Int
def y: Int
def z: Int
/** Return the bounds of the part for texture mapping side decals like grass
*/
def getRenderBounds: Cuboid6
} }
@@ -1,13 +1,15 @@
package codechicken.microblock package codechicken.microblock
/** /** Implement this on center parts that connect through hollow covers to have
* Implement this on center parts that connect through hollow covers to have the covers render their hollows to fit the connection size * the covers render their hollows to fit the connection size
*/ */
trait ISidedHollowConnect trait ISidedHollowConnect {
{
/** /** @param side
* @param side The side of the block on which the cover resides * The side of the block on which the cover resides
* @return The size (width and height) of the connection in pixels. Must be be less than 12 and more than 0 * @return
*/ * The size (width and height) of the connection in pixels. Must be be less
def getHollowSize(side:Int):Int * than 12 and more than 0
*/
def getHollowSize(side: Int): Int
} }
@@ -23,148 +23,187 @@ import codechicken.lib.render.TextureUtils
import net.minecraft.util.MovingObjectPosition.MovingObjectType import net.minecraft.util.MovingObjectPosition.MovingObjectType
import CommonMicroClass._ import CommonMicroClass._
class ItemMicroPart extends Item class ItemMicroPart extends Item {
{ setUnlocalizedName("microblock")
setUnlocalizedName("microblock") setHasSubtypes(true)
setHasSubtypes(true)
override def getItemStackDisplayName(stack:ItemStack):String = override def getItemStackDisplayName(stack: ItemStack): String = {
{ val material = getMaterial(stack)
val material = getMaterial(stack) val mcrClass = getMicroClass(stack.getItemDamage)
val mcrClass = getMicroClass(stack.getItemDamage) val size = stack.getItemDamage & 0xff
val size = stack.getItemDamage&0xFF if (material == null || mcrClass == null)
if(material == null || mcrClass == null) return "Unnamed"
return "Unnamed"
return StatCollector.translateToLocalFormatted(mcrClass.getName+"."+size+".name", material.getLocalizedName) return StatCollector.translateToLocalFormatted(
mcrClass.getName + "." + size + ".name",
material.getLocalizedName
)
}
override def getSubItems(item: Item, tab: CreativeTabs, list$ : List[_]) {
val list = list$.asInstanceOf[List[ItemStack]]
for (classId <- 0 until classes.length) {
val mcrClass = classes(classId)
if (mcrClass != null)
for (size <- Seq(1, 2, 4))
MicroMaterialRegistry.getIdMap.foreach(e =>
list.add(create(classId << 8 | size, e._1))
)
} }
}
override def getSubItems(item:Item, tab:CreativeTabs, list$:List[_]) override def registerIcons(register: IIconRegister) {}
{
val list = list$.asInstanceOf[List[ItemStack]]
for(classId <- 0 until classes.length)
{
val mcrClass = classes(classId)
if(mcrClass != null)
for(size <- Seq(1, 2, 4))
MicroMaterialRegistry.getIdMap.foreach(e => list.add(create(classId<<8|size, e._1)))
}
}
override def registerIcons(register:IIconRegister){} override def onItemUse(
item: ItemStack,
override def onItemUse(item:ItemStack, player:EntityPlayer, world:World, x:Int, y:Int, z:Int, s:Int, hitX:Float, hitY:Float, hitZ:Float):Boolean = player: EntityPlayer,
{ world: World,
val material = getMaterialID(item) x: Int,
val mcrClass = getMicroClass(item.getItemDamage) y: Int,
val size = item.getItemDamage&0xFF z: Int,
if(material < 0 || mcrClass == null) s: Int,
return false hitX: Float,
hitY: Float,
val hit = RayTracer.retraceBlock(world, player, x, y, z) hitZ: Float
if(hit != null && hit.typeOfHit == MovingObjectType.BLOCK) ): Boolean = {
{ val material = getMaterialID(item)
val placement = MicroblockPlacement(player, hit, size, material, !player.capabilities.isCreativeMode, mcrClass.placementProperties) val mcrClass = getMicroClass(item.getItemDamage)
if(placement == null) val size = item.getItemDamage & 0xff
return false if (material < 0 || mcrClass == null)
return false
if(!world.isRemote)
{
placement.place(world, player, item)
if(!player.capabilities.isCreativeMode)
placement.consume(world, player, item)
val sound = MicroMaterialRegistry.getMaterial(material).getSound
if(sound != null)
world.playSoundEffect(placement.pos.x + 0.5D, placement.pos.y + 0.5D, placement.pos.z + 0.5D, sound.func_150496_b, (sound.getVolume + 1.0F) / 2.0F, sound.getPitch * 0.8F)
}
return true
}
val hit = RayTracer.retraceBlock(world, player, x, y, z)
if (hit != null && hit.typeOfHit == MovingObjectType.BLOCK) {
val placement = MicroblockPlacement(
player,
hit,
size,
material,
!player.capabilities.isCreativeMode,
mcrClass.placementProperties
)
if (placement == null)
return false return false
if (!world.isRemote) {
placement.place(world, player, item)
if (!player.capabilities.isCreativeMode)
placement.consume(world, player, item)
val sound = MicroMaterialRegistry.getMaterial(material).getSound
if (sound != null)
world.playSoundEffect(
placement.pos.x + 0.5d,
placement.pos.y + 0.5d,
placement.pos.z + 0.5d,
sound.func_150496_b,
(sound.getVolume + 1.0f) / 2.0f,
sound.getPitch * 0.8f
)
}
return true
} }
return false
}
} }
object ItemMicroPart object ItemMicroPart {
{ def checkTagCompound(stack: ItemStack) {
def checkTagCompound(stack:ItemStack) if (!stack.hasTagCompound)
{ stack.setTagCompound(new NBTTagCompound())
if(!stack.hasTagCompound) }
stack.setTagCompound(new NBTTagCompound())
def create(damage: Int, material: Int): ItemStack =
create(damage, MicroMaterialRegistry.materialName(material))
def create(damage: Int, material: String): ItemStack =
create(1, damage, material)
def create(amount: Int, damage: Int, material: String): ItemStack = {
val stack = new ItemStack(MicroblockProxy.itemMicro, amount, damage)
checkTagCompound(stack)
stack.getTagCompound.setString("mat", material)
return stack
}
def getMaterial(stack: ItemStack): IMicroMaterial = {
checkTagCompound(stack)
if (!stack.getTagCompound.hasKey("mat"))
return null
MicroMaterialRegistry.getMaterial(
stack.getTagCompound.getString("mat")
) match {
case null => MissingMicroMaterial
case mat => mat
} }
}
def create(damage:Int, material:Int):ItemStack = create(damage, MicroMaterialRegistry.materialName(material)) def getMaterialID(stack: ItemStack): Int = {
checkTagCompound(stack)
if (!stack.getTagCompound.hasKey("mat"))
return MicroMaterialRegistry.getMissingId
def create(damage:Int, material:String):ItemStack = create(1, damage, material) return MicroMaterialRegistry.materialID(
stack.getTagCompound.getString("mat")
def create(amount:Int, damage:Int, material:String):ItemStack = )
{ }
val stack = new ItemStack(MicroblockProxy.itemMicro, amount, damage)
checkTagCompound(stack)
stack.getTagCompound.setString("mat", material)
return stack
}
def getMaterial(stack:ItemStack):IMicroMaterial =
{
checkTagCompound(stack)
if(!stack.getTagCompound.hasKey("mat"))
return null
return MicroMaterialRegistry.getMaterial(stack.getTagCompound.getString("mat"))
}
def getMaterialID(stack:ItemStack):Int =
{
checkTagCompound(stack)
if(!stack.getTagCompound.hasKey("mat"))
return 0
return MicroMaterialRegistry.materialID(stack.getTagCompound.getString("mat"))
}
} }
object ItemMicroPartRenderer extends IItemRenderer object ItemMicroPartRenderer extends IItemRenderer {
{ def handleRenderType(item: ItemStack, t: ItemRenderType) = true
def handleRenderType(item:ItemStack, t:ItemRenderType) = true
def shouldUseRenderHelper(t:ItemRenderType, item:ItemStack, helper:ItemRendererHelper) = true def shouldUseRenderHelper(
t: ItemRenderType,
item: ItemStack,
helper: ItemRendererHelper
) = true
def renderItem(t:ItemRenderType, item:ItemStack, data:Object*) def renderItem(t: ItemRenderType, item: ItemStack, data: Object*) {
{ val material = getMaterial(item)
val material = getMaterial(item) val mcrClass = getMicroClass(item.getItemDamage)
val mcrClass = getMicroClass(item.getItemDamage) val size = item.getItemDamage & 0xff
val size = item.getItemDamage&0xFF if (material == null || mcrClass == null)
if(material == null || mcrClass == null) return
return
GL11.glPushMatrix() GL11.glPushMatrix()
if(t == ItemRenderType.ENTITY) if (t == ItemRenderType.ENTITY)
GL11.glScaled(0.5, 0.5, 0.5) GL11.glScaled(0.5, 0.5, 0.5)
if(t == ItemRenderType.INVENTORY || t == ItemRenderType.ENTITY) if (t == ItemRenderType.INVENTORY || t == ItemRenderType.ENTITY)
GL11.glTranslatef(-0.5F, -0.5F, -0.5F) GL11.glTranslatef(-0.5f, -0.5f, -0.5f)
TextureUtils.bindAtlas(0)
val state = CCRenderState.instance
state.resetInstance()
state.useNormals = true
state.pullLightmapInstance()
state.startDrawingInstance()
val part =
mcrClass.create(true, getMaterialID(item)).asInstanceOf[MicroblockClient]
part.setShape(size, mcrClass.itemSlot)
part.render(new Vector3(0.5, 0.5, 0.5).subtract(part.getBounds.center), -1)
state.drawInstance()
GL11.glPopMatrix()
}
TextureUtils.bindAtlas(0) def renderHighlight(
CCRenderState.reset() player: EntityPlayer,
CCRenderState.useNormals = true stack: ItemStack,
CCRenderState.pullLightmap() hit: MovingObjectPosition
CCRenderState.startDrawing() ): Boolean = {
val part = mcrClass.create(true, getMaterialID(item)).asInstanceOf[MicroblockClient] val material = getMaterialID(stack)
part.setShape(size, mcrClass.itemSlot) val mcrClass = getMicroClass(stack.getItemDamage)
part.render(new Vector3(0.5, 0.5, 0.5).subtract(part.getBounds.center), -1) val size = stack.getItemDamage & 0xff
CCRenderState.draw() if (material < 0 || mcrClass == null)
GL11.glPopMatrix() return false
}
def renderHighlight(player:EntityPlayer, stack:ItemStack, hit:MovingObjectPosition):Boolean = return MicroMaterialRegistry.renderHighlight(
{ player,
val material = getMaterialID(stack) hit,
val mcrClass = getMicroClass(stack.getItemDamage) mcrClass,
val size = stack.getItemDamage&0xFF size,
if(material < 0 || mcrClass == null) material
return false )
}
return MicroMaterialRegistry.renderHighlight(player, hit, mcrClass, size, material)
}
} }
@@ -21,79 +21,116 @@ import net.minecraft.client.renderer.texture.{TextureMap, IIconRegister}
import codechicken.lib.render.uv.UVTranslation import codechicken.lib.render.uv.UVTranslation
import codechicken.microblock.handler.MicroblockProxy import codechicken.microblock.handler.MicroblockProxy
/** /** Interface for items that are 'saws'
* Interface for items that are 'saws' */
*/ trait Saw extends Item {
trait Saw extends Item
{ /** The maximum harvest level that some version of this saw is capable of
/** * cutting
* The maximum harvest level that some version of this saw is capable of cutting */
*/ def getMaxCuttingStrength: Int = getCuttingStrength(new ItemStack(this))
def getMaxCuttingStrength:Int = getCuttingStrength(new ItemStack(this))
/** /** The harvest level this saw is capable of cutting
* The harvest level this saw is capable of cutting */
*/ def getCuttingStrength(item: ItemStack): Int
def getCuttingStrength(item:ItemStack):Int
} }
class ItemSaw(sawTag:ConfigTag, val harvestLevel:Int) extends Item with Saw class ItemSaw(sawTag: ConfigTag, val harvestLevel: Int) extends Item with Saw {
{ {
{ val maxDamage =
val maxDamage = sawTag.getTag("durability").getIntValue(1<<harvestLevel+8) sawTag.getTag("durability").getIntValue(1 << harvestLevel + 8)
if(maxDamage > 0) if (maxDamage > 0)
setMaxDamage(maxDamage) setMaxDamage(maxDamage)
setNoRepair() setNoRepair()
setMaxStackSize(1) setMaxStackSize(1)
setCreativeTab(net.minecraft.creativetab.CreativeTabs.tabTools) setCreativeTab(net.minecraft.creativetab.CreativeTabs.tabTools)
} }
override def hasContainerItem = true override def hasContainerItem = true
override def getContainerItem(stack:ItemStack) = override def getContainerItem(stack: ItemStack) =
if(isDamageable) if (isDamageable)
new ItemStack(stack.getItem, 1, stack.getItemDamage+1) new ItemStack(stack.getItem, 1, stack.getItemDamage + 1)
else else
stack stack
override def doesContainerItemLeaveCraftingGrid(stack:ItemStack) = false override def doesContainerItemLeaveCraftingGrid(stack: ItemStack) = false
def getCuttingStrength(item:ItemStack) = harvestLevel def getCuttingStrength(item: ItemStack) = harvestLevel
} }
object ItemSawRenderer extends IItemRenderer object ItemSawRenderer extends IItemRenderer {
{ val models = CCModel.parseObjModels(
val models = CCModel.parseObjModels(new ResourceLocation("microblock", "models/saw.obj"), 7, new SwapYZ()) new ResourceLocation("microblock", "models/saw.obj"),
val handle = models.get("Handle") 7,
val holder = models.get("BladeSupport") new SwapYZ()
val blade = models.get("Blade") )
val handle = models.get("Handle")
def handleRenderType(item:ItemStack, renderType:ItemRenderType) = val holder = models.get("BladeSupport")
!MicroblockProxy.useSawIcons || TextureUtils.isMissing(item.getIconIndex, TextureMap.locationItemsTexture) val blade = models.get("Blade")
def shouldUseRenderHelper(renderType:ItemRenderType, item:ItemStack, helper:ItemRendererHelper) = true def handleRenderType(item: ItemStack, renderType: ItemRenderType) =
!MicroblockProxy.useSawIcons || TextureUtils.isMissing(
def renderItem(renderType:ItemRenderType, item:ItemStack, data:Object*) item.getIconIndex,
{ TextureMap.locationItemsTexture
val t = renderType match { )
case INVENTORY => new TransformationList(new Scale(1.8), new Translation(0, 0, -0.6), new Rotation(-pi/4, 1, 0, 0), new Rotation(pi*3/4, 0, 1, 0))
case ENTITY => new TransformationList(new Scale(1), new Translation(0, 0, -0.25), new Rotation(-pi/4, 1, 0, 0)) def shouldUseRenderHelper(
case EQUIPPED_FIRST_PERSON => new TransformationList(new Scale(1.5), new Rotation(-pi/3, 1, 0, 0), new Rotation(pi*3/4, 0, 1, 0), new Translation(0.5, 0.5, 0.5)) renderType: ItemRenderType,
case EQUIPPED => new TransformationList(new Scale(1.5), new Rotation(-pi/5, 1, 0, 0), new Rotation(-pi*3/4, 0, 1, 0), new Translation(0.75, 0.5, 0.75)) item: ItemStack,
case _ => return helper: ItemRendererHelper
} ) = true
CCRenderState.reset() def renderItem(renderType: ItemRenderType, item: ItemStack, data: Object*) {
CCRenderState.useNormals = true val t = renderType match {
CCRenderState.pullLightmap() case INVENTORY =>
CCRenderState.changeTexture("microblock:textures/items/saw.png") new TransformationList(
CCRenderState.startDrawing() new Scale(1.8),
handle.render(t) new Translation(0, 0, -0.6),
holder.render(t) new Rotation(-pi / 4, 1, 0, 0),
CCRenderState.draw() new Rotation(pi * 3 / 4, 0, 1, 0)
GL11.glDisable(GL11.GL_CULL_FACE) )
CCRenderState.startDrawing() case ENTITY =>
blade.render(t, new UVTranslation(0, (item.getItem.asInstanceOf[Saw].getCuttingStrength(item)-1)*4/64D)) new TransformationList(
CCRenderState.draw() new Scale(1),
GL11.glEnable(GL11.GL_CULL_FACE) new Translation(0, 0, -0.25),
new Rotation(-pi / 4, 1, 0, 0)
)
case EQUIPPED_FIRST_PERSON =>
new TransformationList(
new Scale(1.5),
new Rotation(-pi / 3, 1, 0, 0),
new Rotation(pi * 3 / 4, 0, 1, 0),
new Translation(0.5, 0.5, 0.5)
)
case EQUIPPED =>
new TransformationList(
new Scale(1.5),
new Rotation(-pi / 5, 1, 0, 0),
new Rotation(-pi * 3 / 4, 0, 1, 0),
new Translation(0.75, 0.5, 0.75)
)
case _ => return
} }
val state = CCRenderState.instance
state.resetInstance()
state.useNormals = true
state.pullLightmapInstance()
CCRenderState.changeTexture("microblock:textures/items/saw.png")
state.startDrawingInstance()
handle.render(t)
holder.render(t)
state.drawInstance()
GL11.glDisable(GL11.GL_CULL_FACE)
state.startDrawingInstance()
blade.render(
t,
new UVTranslation(
0,
(item.getItem.asInstanceOf[Saw].getCuttingStrength(item) - 1) * 4 / 64d
)
)
state.drawInstance()
GL11.glEnable(GL11.GL_CULL_FACE)
}
} }
@@ -19,222 +19,237 @@ import scala.collection.JavaConversions._
import java.util.{Iterator => JIterator} import java.util.{Iterator => JIterator}
import net.minecraft.block.Block.SoundType import net.minecraft.block.Block.SoundType
object MicroMaterialRegistry object MicroMaterialRegistry {
{
/**
* Interface for defining a micro material
*/
trait IMicroMaterial
{
/**
* The icon to be used for breaking particles on side
*/
@SideOnly(Side.CLIENT)
def getBreakingIcon(side: Int): IIcon
/** /** Interface for defining a micro material
* Callback to load icons from the underlying block/etc */
*/ trait IMicroMaterial {
@SideOnly(Side.CLIENT)
def loadIcons() {}
/** /** The icon to be used for breaking particles on side
* This function must configure and use the CCRenderState pipeline to draw from the current vertex source. */
* CCRenderState.lightMatrix will be set. @SideOnly(Side.CLIENT)
* @param pass The current render pass, -1 for inventory rendering def getBreakingIcon(side: Int): IIcon
* @param bounds The cuboid bounds of the face being rendered
*/
@SideOnly(Side.CLIENT)
def renderMicroFace(pos: Vector3, pass: Int, bounds: Cuboid6)
/** /** Callback to load icons from the underlying block/etc
* Get the render pass for which this material renders in. */
*/ @SideOnly(Side.CLIENT)
@SideOnly(Side.CLIENT) def loadIcons() {}
def canRenderInPass(pass: Int) = pass == 0
/** /** This function must configure and use the CCRenderState pipeline to draw
* Return true if this material is not opaque (glass, ice). * from the current vertex source. CCRenderState.lightMatrix will be set.
*/ * @param pass
def isTransparent: Boolean * The current render pass, -1 for inventory rendering
* @param bounds
* The cuboid bounds of the face being rendered
*/
@SideOnly(Side.CLIENT)
def renderMicroFace(pos: Vector3, pass: Int, bounds: Cuboid6)
/** /** Get the render pass for which this material renders in.
* Return the light level emitted by this material (glowstone) */
*/ @SideOnly(Side.CLIENT)
def getLightValue: Int def canRenderInPass(pass: Int) = pass == 0
/** /** Return true if this material is not opaque (glass, ice).
* Return the strength of this material */
*/ def isTransparent: Boolean
def getStrength(player: EntityPlayer): Float
/** /** Return the light level emitted by this material (glowstone)
* Return the localised name of this material (normally the block name) */
*/ def getLightValue: Int
def getLocalizedName: String
/** /** Return the strength of this material
* Get the item that this material is cut from (full block -> slabs) */
*/ def getStrength(player: EntityPlayer): Float
def getItem: ItemStack
/** /** Return the localised name of this material (normally the block name)
* Get the strength of saw requried to cut this material */
*/ def getLocalizedName: String
def getCutterStrength: Int
/** /** Get the item that this material is cut from (full block -> slabs)
* Get the breaking/walking sound */
*/ def getItem: ItemStack
def getSound: SoundType
/** /** Get the strength of saw requried to cut this material
* Return true if this material is solid and opaque (can run wires on etc) */
*/ def getCutterStrength: Int
def isSolid = !isTransparent
/** /** Get the breaking/walking sound
* Get the explosion resistance of this part to an explosion caused by entity */
*/ def getSound: SoundType
def explosionResistance(entity: Entity): Float
/** Return true if this material is solid and opaque (can run wires on etc)
*/
def isSolid = !isTransparent
/** Get the explosion resistance of this part to an explosion caused by
* entity
*/
def explosionResistance(entity: Entity): Float
}
/** Interface for overriding the default micro placement highlight handler to
* show the effect of placement on a certain block/part
*/
trait IMicroHighlightRenderer {
/** Return true if a custom highlight was rendered and the default should be
* skipped
*/
def renderHighlight(
player: EntityPlayer,
hit: MovingObjectPosition,
mcrClass: CommonMicroClass,
size: Int,
material: Int
): Boolean
}
private val typeMap = HashMap[String, IMicroMaterial]()
private val nameMap = HashMap[String, Int]()
private var idMap: Array[(String, IMicroMaterial)] = _
private val idWriter = new IDWriter
private val highlightRenderers = ListBuffer[IMicroHighlightRenderer]()
private var maxCuttingStrength: Int = _
private val remap = HashMap[String, String]()
private var missingId: Int = 0
/** Register a micro material with unique identifier name
*/
def registerMaterial(material: IMicroMaterial, name: String) {
if (MultiPartRegistry.loaded)
throw new IllegalStateException(
"You must register your materials in the init methods."
)
if (typeMap.contains(name)) {
logger.error("Material with id " + name + " is already registered.")
return
} }
/** typeMap.put(name, material)
* Interface for overriding the default micro placement highlight handler to show the effect of placement on a certain block/part }
*/
trait IMicroHighlightRenderer /** Replace a micro material with unique identifier name
{ */
/** def replaceMaterial(material: IMicroMaterial, name: String) {
* Return true if a custom highlight was rendered and the default should be skipped if (MultiPartRegistry.loaded)
*/ throw new IllegalStateException(
def renderHighlight(player: EntityPlayer, hit: MovingObjectPosition, mcrClass: CommonMicroClass, size: Int, material: Int): Boolean "You must register your materials in the init methods."
)
if (typeMap.remove(name).isEmpty)
logger.error("Material with id " + name + " was not registered.")
logger.debug("Replaced micro material: " + name)
typeMap.put(name, material)
}
/** Registers a highlight renderer
*/
def registerHighlightRenderer(handler: IMicroHighlightRenderer) {
highlightRenderers += handler
}
def remapName(oldName: String, newName: String): Unit =
remap.put(oldName, newName)
private[microblock] def setupIDMap() {
idMap = typeMap.toList.sortBy(_._1).toArray
idWriter.setMax(idMap.length)
nameMap.clear()
for (i <- 0 until idMap.length)
nameMap.put(idMap(i)._1, i)
missingId = nameMap.getOrElse(
MissingMicroMaterial.key,
throw new IllegalStateException(
"MissingMicroMaterial is not registered; the placeholder must never " +
"fall back to id 0."
)
)
}
def getMissingId = missingId
private[microblock] def calcMaxCuttingStrength() {
val it = Item.itemRegistry.iterator.asInstanceOf[JIterator[Item]]
maxCuttingStrength = it.flatMap {
case saw: Saw => Some(saw.getMaxCuttingStrength)
case _ => None
}.max
}
private[microblock] def loadIcons() {
if (idMap != null)
idMap.foreach(e => e._2.loadIcons())
}
def getMaxCuttingStrength = maxCuttingStrength
def writeIDMap(packet: PacketCustom) {
packet.writeInt(idMap.size)
idMap.foreach(e => packet.writeString(e._1))
}
def readIDMap(packet: PacketCustom): Seq[String] = {
val k = packet.readInt()
idWriter.setMax(k)
idMap = new Array(k)
nameMap.clear()
val missing = ListBuffer[String]()
for (i <- 0 until k) {
val s = packet.readString()
val v = typeMap.get(s)
if (v.isEmpty)
missing += s
else {
idMap(i) = (s, v.get)
nameMap.put(s, i)
}
}
return missing
}
def writeMaterialID(data: MCDataOutput, id: Int) {
idWriter.write(data, id)
}
def readMaterialID(data: MCDataInput) = idWriter.read(data)
def materialName(id: Int) = idMap(id)._1
def materialID(name: String) =
nameMap.get(remap.getOrElse(name, name)) match {
case Some(v) => v
case None =>
logger.error("Missing mapping for part with ID: " + name)
missingId
} }
private val typeMap = HashMap[String, IMicroMaterial]() def getMaterial(name: String) =
private val nameMap = HashMap[String, Int]() typeMap.getOrElse(remap.getOrElse(name, name), null)
private var idMap: Array[(String, IMicroMaterial)] = _
private val idWriter = new IDWriter
private val highlightRenderers = ListBuffer[IMicroHighlightRenderer]() def getMaterial(id: Int) = idMap(id)._2
private var maxCuttingStrength: Int = _
private val remap = HashMap[String, String]() def getIdMap = idMap
/** def renderHighlight(
* Register a micro material with unique identifier name player: EntityPlayer,
*/ hit: MovingObjectPosition,
def registerMaterial(material: IMicroMaterial, name: String) { mcrClass: CommonMicroClass,
if (MultiPartRegistry.loaded) size: Int,
throw new IllegalStateException("You must register your materials in the init methods.") material: Int
): Boolean = {
val overridden = highlightRenderers.find(
_.renderHighlight(player, hit, mcrClass, size, material)
)
if (overridden.isDefined)
return true
if (typeMap.contains(name)) { MicroblockRender.renderHighlight(player, hit, mcrClass, size, material)
logger.error("Material with id " + name + " is already registered.") return true
return }
}
logger.debug("Registered micro material: " + name)
typeMap.put(name, material)
}
/**
* Replace a micro material with unique identifier name
*/
def replaceMaterial(material: IMicroMaterial, name: String) {
if (MultiPartRegistry.loaded)
throw new IllegalStateException("You must register your materials in the init methods.")
if (typeMap.remove(name).isEmpty)
logger.error("Material with id " + name + " was not registered.")
logger.debug("Replaced micro material: " + name)
typeMap.put(name, material)
}
/**
* Registers a highlight renderer
*/
def registerHighlightRenderer(handler: IMicroHighlightRenderer) {
highlightRenderers += handler
}
def remapName(oldName:String, newName:String):Unit = remap.put(oldName, newName)
private[microblock] def setupIDMap() {
idMap = typeMap.toList.sortBy(_._1).toArray
idWriter.setMax(idMap.length)
nameMap.clear()
for (i <- 0 until idMap.length)
nameMap.put(idMap(i)._1, i)
}
private[microblock] def calcMaxCuttingStrength() {
val it = Item.itemRegistry.iterator.asInstanceOf[JIterator[Item]]
maxCuttingStrength = it.flatMap {
case saw: Saw => Some(saw.getMaxCuttingStrength)
case _ => None
}.max
}
private[microblock] def loadIcons() {
if(idMap != null)
idMap.foreach(e => e._2.loadIcons())
}
def getMaxCuttingStrength = maxCuttingStrength
def writeIDMap(packet: PacketCustom) {
packet.writeInt(idMap.size)
idMap.foreach(e => packet.writeString(e._1))
}
def readIDMap(packet: PacketCustom): Seq[String] = {
val k = packet.readInt()
idWriter.setMax(k)
idMap = new Array(k)
nameMap.clear()
val missing = ListBuffer[String]()
for (i <- 0 until k) {
val s = packet.readString()
val v = typeMap.get(s)
if (v.isEmpty)
missing += s
else {
idMap(i) = (s, v.get)
nameMap.put(s, i)
}
}
return missing
}
def writeMaterialID(data: MCDataOutput, id: Int) {
idWriter.write(data, id)
}
def readMaterialID(data: MCDataInput) = idWriter.read(data)
def materialName(id: Int) = idMap(id)._1
def materialID(name: String) = nameMap.get(remap.getOrElse(name, name)) match {
case Some(v) => v
case None =>
logger.error("Missing mapping for part with ID: " + name)
0
}
def getMaterial(name: String) = typeMap.getOrElse(remap.getOrElse(name, name), null)
def getMaterial(id: Int) = idMap(id)._2
def getIdMap = idMap
def renderHighlight(player: EntityPlayer, hit: MovingObjectPosition, mcrClass: CommonMicroClass, size: Int, material: Int): Boolean = {
val overridden = highlightRenderers.find(_.renderHighlight(player, hit, mcrClass, size, material))
if (overridden.isDefined)
return true
MicroblockRender.renderHighlight(player, hit, mcrClass, size, material)
return true
}
} }
@@ -7,221 +7,241 @@ import net.minecraft.item.ItemStack
import codechicken.microblock.handler.MicroblockProxy._ import codechicken.microblock.handler.MicroblockProxy._
import net.minecraftforge.oredict.RecipeSorter import net.minecraftforge.oredict.RecipeSorter
object MicroRecipe extends IRecipe object MicroRecipe extends IRecipe {
{ RecipeSorter.register(
RecipeSorter.register("fmp:micro", getClass, RecipeSorter.Category.SHAPED, "after:forge:shapelessore") "fmp:micro",
getClass,
RecipeSorter.Category.SHAPED,
"after:forge:shapelessore"
)
def getRecipeOutput = ItemMicroPart.create(1, 1, "tile.stone") def getRecipeOutput = ItemMicroPart.create(1, 1, "tile.stone")
def getRecipeSize = 9 def getRecipeSize = 9
def matches(icraft:InventoryCrafting, world:World) = getCraftingResult(icraft) != null def matches(icraft: InventoryCrafting, world: World) =
getCraftingResult(icraft) != null
def getCraftingResult(icraft:InventoryCrafting):ItemStack = def getCraftingResult(icraft: InventoryCrafting): ItemStack = {
{ var res = getHollowResult(icraft)
var res = getHollowResult(icraft) if (res != null) return res
if(res != null) return res res = getGluingResult(icraft)
res = getGluingResult(icraft) if (res != null) return res
if(res != null) return res res = getThinningResult(icraft)
res = getThinningResult(icraft) if (res != null) return res
if(res != null) return res res = getSplittingResult(icraft)
res = getSplittingResult(icraft) if (res != null) return res
if(res != null) return res res = getHollowFillResult(icraft)
res = getHollowFillResult(icraft) return res
return res }
def create(
amount: Int,
mcrClass: Int,
size: Int,
material: Int
): ItemStack = {
if (size == 8) {
val item = MicroMaterialRegistry.getMaterial(material).getItem.copy
item.stackSize = amount
return item
} }
return ItemMicroPart.create(
amount,
mcrClass << 8 | size,
MicroMaterialRegistry.materialName(material)
)
}
def create(amount:Int, mcrClass:Int, size:Int, material:Int):ItemStack = def microMaterial(item: ItemStack) =
{ if (item.getItem == itemMicro)
if(size == 8) ItemMicroPart.getMaterialID(item)
{ else
val item = MicroMaterialRegistry.getMaterial(material).getItem.copy findMaterial(item)
item.stackSize = amount
return item def microClass(item: ItemStack) =
if (item.getItem == itemMicro)
item.getItemDamage >> 8
else
0
def microSize(item: ItemStack) =
if (item.getItem == itemMicro)
item.getItemDamage & 0xff
else
8
def getHollowResult(icraft: InventoryCrafting): ItemStack = {
if (icraft.getStackInRowAndColumn(1, 1) != null) return null
val first = icraft.getStackInRowAndColumn(0, 0)
if (first == null || first.getItem != itemMicro || microClass(first) != 0)
return null
val size = microSize(first)
val material = microMaterial(first)
for (i <- 1 to 8 if i != 4) {
val item = icraft.getStackInSlot(i)
if (
item == null || item.getItem != itemMicro ||
microMaterial(
item
) != material || item.getItemDamage != first.getItemDamage
)
return null
}
return create(8, 1, size, material)
}
def getGluingResult(icraft: InventoryCrafting): ItemStack = {
var size = 0
var count = 0
var smallest = 0
var mcrClass = 0
var material = 0
for (i <- 0 until 9) {
val item = icraft.getStackInSlot(i)
if (item != null) {
if (item.getItem != itemMicro) return null
if (count == 0) {
size = microSize(item)
mcrClass = microClass(item)
material = microMaterial(item)
count = 1
smallest = size
} else if (
microClass(item) != mcrClass || microMaterial(item) != material
) return null
else if (mcrClass >= 2 && microSize(item) != smallest) return null
else {
smallest = Math.min(smallest, microSize(item))
count += 1
size += microSize(item)
} }
return ItemMicroPart.create(amount, mcrClass<<8|size, MicroMaterialRegistry.materialName(material)) }
} }
def microMaterial(item:ItemStack) = if (count <= 1) return null
if(item.getItem == itemMicro)
ItemMicroPart.getMaterialID(item) mcrClass match {
case 3 =>
count match {
case 2 => create(1, 0, smallest, material)
case _ => null
}
case 2 =>
count match {
case 2 => create(1, 3, smallest, material)
case 4 => create(1, 0, smallest, material)
case _ => null
}
case 1 | 0 =>
val base = Seq(1, 2, 4).find(s => (s & size) != 0)
if (base.isEmpty)
create(size / 8, 0, 8, material)
else if (base.get <= smallest)
null
else else
findMaterial(item) create(size / base.get, mcrClass, base.get, material)
case _ => null
}
}
def microClass(item:ItemStack) = def getSaw(icraft: InventoryCrafting): (Saw, Int, Int) = {
if(item.getItem == itemMicro) for (r <- 0 until 3)
item.getItemDamage >> 8 for (c <- 0 until 3) {
else val item = icraft.getStackInRowAndColumn(c, r)
0 if (item != null && item.getItem.isInstanceOf[Saw])
return (item.getItem.asInstanceOf[Saw], r, c)
}
return (null, 0, 0)
}
def microSize(item:ItemStack) = def canCut(saw: Saw, sawItem: ItemStack, material: Int): Boolean = {
if(item.getItem == itemMicro) val sawStrength = saw.getCuttingStrength(sawItem)
item.getItemDamage & 0xFF val matStrength =
else MicroMaterialRegistry.getMaterial(material).getCutterStrength
8 return sawStrength >= matStrength || sawStrength == MicroMaterialRegistry.getMaxCuttingStrength
}
def getHollowResult(icraft:InventoryCrafting):ItemStack = def getThinningResult(icraft: InventoryCrafting): ItemStack = {
{ val (saw, row, col) = getSaw(icraft)
if(icraft.getStackInRowAndColumn(1, 1) != null) return null if (saw == null)
return null
val first = icraft.getStackInRowAndColumn(0, 0) val item = icraft.getStackInRowAndColumn(col, row + 1)
if(first == null || first.getItem != itemMicro || microClass(first) != 0) return null if (item == null)
val size = microSize(first) return null
val material = microMaterial(first)
for(i <- 1 to 8 if i != 4) val size = microSize(item)
{ val material = microMaterial(item)
val item = icraft.getStackInSlot(i) val mcrClass = microClass(item)
if(item == null || item.getItem != itemMicro || if (
microMaterial(item) != material || item.getItemDamage != first.getItemDamage) size == 1 || material < 0 || !canCut(
return null saw,
} icraft.getStackInRowAndColumn(col, row),
return create(8, 1, size, material) material
)
)
return null
for (r <- 0 until 3)
for (c <- 0 until 3)
if (
(c != col || r != row && r != row + 1) &&
icraft.getStackInRowAndColumn(c, r) != null
)
return null
return create(2, mcrClass, size / 2, material)
}
def findMaterial(item: ItemStack): Int =
MicroMaterialRegistry.getIdMap.find { m =>
val mitem = m._2.getItem
m._2 != MissingMicroMaterial && item.getItem == mitem.getItem &&
item.getItemDamage == mitem.getItemDamage &&
ItemStack.areItemStackTagsEqual(item, mitem)
} match {
case None => -1
case Some((name, m)) => MicroMaterialRegistry.materialID(name)
} }
def getGluingResult(icraft:InventoryCrafting):ItemStack = val splitMap = Map(0 -> 3, 1 -> 3, 3 -> 2)
{ def getSplittingResult(icraft: InventoryCrafting): ItemStack = {
var size = 0 val (saw, row, col) = getSaw(icraft)
var count = 0 if (saw == null) return null
var smallest = 0 val item = icraft.getStackInRowAndColumn(col + 1, row)
var mcrClass = 0 if (item == null || item.getItem != itemMicro) return null
var material = 0 val mcrClass = microClass(item)
for(i <- 0 until 9) val material = microMaterial(item)
{ if (!canCut(saw, icraft.getStackInRowAndColumn(col, row), material))
val item = icraft.getStackInSlot(i) return null
if(item != null) val split = splitMap.get(mcrClass)
{ if (split.isEmpty) return null
if(item.getItem != itemMicro) return null
if(count == 0)
{
size = microSize(item)
mcrClass = microClass(item)
material = microMaterial(item)
count = 1
smallest = size
}
else if(microClass(item) != mcrClass || microMaterial(item) != material) return null
else if(mcrClass >= 2 && microSize(item) != smallest) return null
else
{
smallest= Math.min(smallest, microSize(item))
count+=1
size+=microSize(item)
}
}
}
if(count <= 1) return null for (r <- 0 until 3)
for (c <- 0 until 3)
if (
(r != row || c != col && c != col + 1) &&
icraft.getStackInRowAndColumn(c, r) != null
)
return null
mcrClass match { return create(2, split.get, microSize(item), material)
case 3 => count match { }
case 2 => create(1, 0, smallest, material)
case _ => null def getHollowFillResult(icraft: InventoryCrafting): ItemStack = {
} var cover: ItemStack = null
case 2 => count match { for (i <- 0 until 9) {
case 2 => create(1, 3, smallest, material) val item = icraft.getStackInSlot(i)
case 4 => create(1, 0, smallest, material) if (item != null) {
case _ => null if (item.getItem != itemMicro || cover != null || microClass(item) != 1)
} return null
case 1|0 => else cover = item
val base = Seq(1, 2, 4).find(s => (s&size) != 0) }
if(base.isEmpty)
create(size/8, 0, 8, material)
else if(base.get <= smallest)
null
else
create(size/base.get, mcrClass, base.get, material)
case _ => null
}
}
def getSaw(icraft:InventoryCrafting):(Saw, Int, Int) =
{
for(r <- 0 until 3)
for(c <- 0 until 3)
{
val item = icraft.getStackInRowAndColumn(c, r)
if(item != null && item.getItem.isInstanceOf[Saw])
return (item.getItem.asInstanceOf[Saw], r, c)
}
return (null, 0, 0)
}
def canCut(saw:Saw, sawItem:ItemStack, material:Int):Boolean = {
val sawStrength = saw.getCuttingStrength(sawItem)
val matStrength = MicroMaterialRegistry.getMaterial(material).getCutterStrength
return sawStrength >= matStrength || sawStrength == MicroMaterialRegistry.getMaxCuttingStrength
}
def getThinningResult(icraft:InventoryCrafting):ItemStack =
{
val (saw, row, col) = getSaw(icraft)
if(saw == null)
return null
val item = icraft.getStackInRowAndColumn(col, row+1)
if(item == null)
return null
val size = microSize(item)
val material = microMaterial(item)
val mcrClass = microClass(item)
if(size == 1 || material < 0 || !canCut(saw, icraft.getStackInRowAndColumn(col, row), material))
return null
for(r <- 0 until 3)
for(c <- 0 until 3)
if((c != col || r != row && r != row+1) &&
icraft.getStackInRowAndColumn(c, r) != null)
return null
return create(2, mcrClass, size/2, material)
}
def findMaterial(item:ItemStack):Int =
MicroMaterialRegistry.getIdMap.find{m => val mitem = m._2.getItem
item.getItem == mitem.getItem &&
item.getItemDamage == mitem.getItemDamage &&
ItemStack.areItemStackTagsEqual(item, mitem)} match {
case None => -1
case Some((name, m)) => MicroMaterialRegistry.materialID(name)
}
val splitMap = Map(0 -> 3, 1 -> 3, 3 -> 2)
def getSplittingResult(icraft:InventoryCrafting):ItemStack =
{
val (saw, row, col) = getSaw(icraft)
if(saw == null) return null
val item = icraft.getStackInRowAndColumn(col+1, row)
if(item == null || item.getItem != itemMicro) return null
val mcrClass = microClass(item)
val material = microMaterial(item)
if(!canCut(saw, icraft.getStackInRowAndColumn(col, row), material)) return null
val split = splitMap.get(mcrClass)
if(split.isEmpty)return null
for(r <- 0 until 3)
for(c <- 0 until 3)
if((r != row || c != col && c != col+1) &&
icraft.getStackInRowAndColumn(c, r) != null)
return null
return create(2, split.get, microSize(item), material)
}
def getHollowFillResult(icraft:InventoryCrafting):ItemStack =
{
var cover:ItemStack = null
for(i <- 0 until 9)
{
val item = icraft.getStackInSlot(i)
if(item != null)
{
if(item.getItem != itemMicro || cover != null || microClass(item) != 1) return null
else cover = item
}
}
if(cover == null) return null
return create(1, 0, microSize(cover), microMaterial(cover))
} }
if (cover == null) return null
return create(1, 0, microSize(cover), microMaterial(cover))
}
} }
@@ -31,128 +31,147 @@ import net.minecraft.init.Blocks
import cpw.mods.fml.relauncher.{Side, SideOnly} import cpw.mods.fml.relauncher.{Side, SideOnly}
import codechicken.lib.render.BlockRenderer.BlockFace import codechicken.lib.render.BlockRenderer.BlockFace
abstract class Microblock(var material:Int = 0) extends TCuboidPart abstract class Microblock(var material: Int = 0) extends TCuboidPart {
{ var shape: Byte = 0
var shape:Byte = 0
def microClass:MicroblockClass def microClass: MicroblockClass
def getType = microClass.getName def getType = microClass.getName
override def getStrength(hit:MovingObjectPosition, player:EntityPlayer) = getIMaterial match { override def getStrength(hit: MovingObjectPosition, player: EntityPlayer) =
case null => super.getStrength(hit, player) getIMaterial match {
case mat => mat.getStrength(player) case null => super.getStrength(hit, player)
case mat => mat.getStrength(player)
} }
override def doesTick = false override def doesTick = false
def getSize = shape>>4 def getSize = shape >> 4
def getShape = shape&0xF def getShape = shape & 0xf
def setShape(size:Int, slot:Int) = shape = (size<<4|slot).toByte def setShape(size: Int, slot: Int) = shape = (size << 4 | slot).toByte
def getMaterial = material def getMaterial = material
def getIMaterial = MicroMaterialRegistry.getMaterial(material) def getIMaterial = MicroMaterialRegistry.getMaterial(material)
def itemClassID:Int def itemClassID: Int
override def getDrops = { override def getDrops = {
var size = getSize var size = getSize
val items = ListBuffer[ItemStack]() val items = ListBuffer[ItemStack]()
for(s <- Seq(4, 2, 1)) for (s <- Seq(4, 2, 1)) {
{ val m = size / s
val m = size/s size -= m * s
size-=m*s if (m > 0)
if(m > 0) items += ItemMicroPart.create(
items+=ItemMicroPart.create(m, s|itemClassID<<8, MicroMaterialRegistry.materialName(material)) m,
} s | itemClassID << 8,
items MicroMaterialRegistry.materialName(material)
)
} }
items
}
override def pickItem(hit:MovingObjectPosition):ItemStack = { override def pickItem(hit: MovingObjectPosition): ItemStack = {
val size = getSize val size = getSize
for(s <- Seq(4, 2, 1)) for (s <- Seq(4, 2, 1))
if(size%s == 0 && size/s >= 1) if (size % s == 0 && size / s >= 1)
return ItemMicroPart.create(s|itemClassID<<8, MicroMaterialRegistry.materialName(material)) return ItemMicroPart.create(
s | itemClassID << 8,
MicroMaterialRegistry.materialName(material)
)
return null//unreachable return null // unreachable
} }
override def writeDesc(packet:MCDataOutput) { override def writeDesc(packet: MCDataOutput) {
writeMaterialID(packet, material) writeMaterialID(packet, material)
packet.writeByte(shape) packet.writeByte(shape)
} }
override def readDesc(packet:MCDataInput) { override def readDesc(packet: MCDataInput) {
shape = packet.readByte shape = packet.readByte
} }
def sendShapeUpdate() { def sendShapeUpdate() {
getWriteStream.writeByte(shape) getWriteStream.writeByte(shape)
} }
override def read(packet:MCDataInput) { override def read(packet: MCDataInput) {
super.read(packet) super.read(packet)
tile.notifyPartChange(this) tile.notifyPartChange(this)
} }
override def save(tag:NBTTagCompound) { override def save(tag: NBTTagCompound) {
tag.setByte("shape", shape) tag.setByte("shape", shape)
tag.setString("material", materialName(material)) tag.setString("material", materialName(material))
} }
override def load(tag:NBTTagCompound) { override def load(tag: NBTTagCompound) {
shape = tag.getByte("shape") shape = tag.getByte("shape")
material = materialID(tag.getString("material")) material = materialID(tag.getString("material"))
} }
def isTransparent = getIMaterial.isTransparent def isTransparent = getIMaterial.isTransparent
override def getLightValue = getIMaterial.getLightValue override def getLightValue = getIMaterial.getLightValue
override def explosionResistance(entity:Entity) = getIMaterial.explosionResistance(entity) * microClass.getResistanceFactor override def explosionResistance(entity: Entity) =
getIMaterial.explosionResistance(entity) * microClass.getResistanceFactor
} }
trait MicroblockClient extends Microblock with TIconHitEffects with IMicroMaterialRender trait MicroblockClient
{ extends Microblock
def getBrokenIcon(side:Int) = getIMaterial match { with TIconHitEffects
case null => Blocks.stone.getIcon(0, 0) with IMicroMaterialRender {
case mat => mat.getBreakingIcon(side) def getBrokenIcon(side: Int) = getIMaterial match {
} case null => Blocks.stone.getIcon(0, 0)
case mat => mat.getBreakingIcon(side)
}
override def renderStatic(pos:Vector3, pass:Int) = { override def renderStatic(pos: Vector3, pass: Int) = {
if(getIMaterial.canRenderInPass(pass)) { if (getIMaterial.canRenderInPass(pass)) {
render(pos, pass) render(pos, pass)
true true
} } else
else false
false }
}
def render(pos:Vector3, pass:Int) def render(pos: Vector3, pass: Int)
override def getRenderBounds = getBounds override def getRenderBounds = getBounds
} }
trait CommonMicroblockClient extends CommonMicroblock with MicroblockClient with TMicroOcclusionClient trait CommonMicroblockClient
{ extends CommonMicroblock
def render(pos:Vector3, pass:Int) { with MicroblockClient
if(pass < 0) with TMicroOcclusionClient {
MicroblockRender.renderCuboid(pos, getIMaterial, pass, getBounds, 0) def render(pos: Vector3, pass: Int) {
else if (pass < 0)
MicroblockRender.renderCuboid(pos, getIMaterial, pass, renderBounds, renderMask) MicroblockRender.renderCuboid(pos, getIMaterial, pass, getBounds, 0)
} else
MicroblockRender.renderCuboid(
pos,
getIMaterial,
pass,
renderBounds,
renderMask
)
}
} }
trait CommonMicroblock extends Microblock with JPartialOcclusion with TMicroOcclusion with TSlottedPart trait CommonMicroblock
{ extends Microblock
def microClass:CommonMicroClass with JPartialOcclusion
with TMicroOcclusion
with TSlottedPart {
def microClass: CommonMicroClass
def getSlot = getShape def getSlot = getShape
def getSlotMask = 1<<getSlot def getSlotMask = 1 << getSlot
def getPartialOcclusionBoxes = Seq(getBounds) def getPartialOcclusionBoxes = Seq(getBounds)
override def itemClassID = microClass.getClassId override def itemClassID = microClass.getClassId
} }
@@ -6,55 +6,58 @@ import net.minecraft.nbt.NBTTagCompound
import codechicken.lib.data.MCDataInput import codechicken.lib.data.MCDataInput
import cpw.mods.fml.relauncher.{Side, SideOnly} import cpw.mods.fml.relauncher.{Side, SideOnly}
abstract class MicroblockClass extends IPartFactory2 abstract class MicroblockClass extends IPartFactory2 {
{ def getName: String
def getName:String def baseTrait: Class[_ <: Microblock]
def baseTrait:Class[_ <: Microblock] @SideOnly(Side.CLIENT)
@SideOnly(Side.CLIENT) def clientTrait: Class[_ <: MicroblockClient]
def clientTrait:Class[_ <: MicroblockClient] def getResistanceFactor: Float
def getResistanceFactor:Float
val baseTraitId = MicroblockGenerator.registerTrait(baseTrait) val baseTraitId = MicroblockGenerator.registerTrait(baseTrait)
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
lazy val clientTraitId = MicroblockGenerator.registerTrait(clientTrait) lazy val clientTraitId = MicroblockGenerator.registerTrait(clientTrait)
def register() { def register() {
MultiPartRegistry.registerParts(this, getName) MultiPartRegistry.registerParts(this, getName)
} }
def create(client:Boolean, material:Int) = MicroblockGenerator.create(this, material, client) def create(client: Boolean, material: Int) =
override def createPart(name: String, packet: MCDataInput) = create(true, MicroMaterialRegistry.readMaterialID(packet)) MicroblockGenerator.create(this, material, client)
override def createPart(name: String, nbt: NBTTagCompound) = create(false, MicroMaterialRegistry.materialID(nbt.getString("material"))) override def createPart(name: String, packet: MCDataInput) =
create(true, MicroMaterialRegistry.readMaterialID(packet))
override def createPart(name: String, nbt: NBTTagCompound) =
create(false, MicroMaterialRegistry.materialID(nbt.getString("material")))
} }
/** /** Microblocks with corresponding items
* Microblocks with corresponding items */
*/ abstract class CommonMicroClass extends MicroblockClass {
abstract class CommonMicroClass extends MicroblockClass private var classId: Int = _
{
private var classId:Int = _
def getClassId = classId def getClassId = classId
def itemSlot:Int def itemSlot: Int
def placementProperties:PlacementProperties def placementProperties: PlacementProperties
def register(id:Int) { def register(id: Int) {
register() register()
classId = id classId = id
CommonMicroClass.registerMicroClass(this, id) CommonMicroClass.registerMicroClass(this, id)
} }
} }
object CommonMicroClass object CommonMicroClass {
{ val classes = new Array[CommonMicroClass](256)
val classes = new Array[CommonMicroClass](256)
def getMicroClass(modelId:Int) = classes(modelId>>8) def getMicroClass(modelId: Int) = classes(modelId >> 8)
def registerMicroClass(mcrClass:CommonMicroClass, id:Int) { def registerMicroClass(mcrClass: CommonMicroClass, id: Int) {
if(classes(id) != null) if (classes(id) != null)
throw new IllegalArgumentException("Microblock class id "+id+" is already taken by "+classes(id).getName+" when adding "+mcrClass.getName) throw new IllegalArgumentException(
"Microblock class id " + id + " is already taken by " + classes(
id
).getName + " when adding " + mcrClass.getName
)
classes(id) = mcrClass classes(id) = mcrClass
} }
} }
@@ -3,23 +3,24 @@ package codechicken.microblock
import codechicken.multipart.asm.{ScratchBitSet, ASMMixinFactory} import codechicken.multipart.asm.{ScratchBitSet, ASMMixinFactory}
import java.util.BitSet import java.util.BitSet
object MicroblockGenerator extends ASMMixinFactory(classOf[Microblock], classOf[Int]) with ScratchBitSet object MicroblockGenerator
{ extends ASMMixinFactory(classOf[Microblock], classOf[Int])
trait IGeneratedMaterial with ScratchBitSet {
{ trait IGeneratedMaterial {
def addTraits(traits:BitSet, mcrClass:MicroblockClass, client:Boolean) def addTraits(traits: BitSet, mcrClass: MicroblockClass, client: Boolean)
}
def create(mcrClass: MicroblockClass, material: Int, client: Boolean) = {
val bitset = freshBitSet
bitset.set(mcrClass.baseTraitId)
if (client) bitset.set(mcrClass.clientTraitId)
MicroMaterialRegistry.getMaterial(material) match {
case genMat: IGeneratedMaterial =>
genMat.addTraits(bitset, mcrClass, client)
case _ =>
} }
def create(mcrClass: MicroblockClass, material: Int, client: Boolean) = { construct(bitset, material: Integer)
val bitset = freshBitSet }
bitset.set(mcrClass.baseTraitId)
if(client) bitset.set(mcrClass.clientTraitId)
MicroMaterialRegistry.getMaterial(material) match {
case genMat:IGeneratedMaterial => genMat.addTraits(bitset, mcrClass, client)
case _ =>
}
construct(bitset, material:Integer)
}
} }
@@ -11,157 +11,170 @@ import net.minecraft.item.ItemStack
import codechicken.multipart.TileMultipart import codechicken.multipart.TileMultipart
import codechicken.lib.raytracer.ExtendedMOP import codechicken.lib.raytracer.ExtendedMOP
abstract class ExecutablePlacement(val pos:BlockCoord, val part:Microblock) abstract class ExecutablePlacement(val pos: BlockCoord, val part: Microblock) {
{ def place(world: World, player: EntityPlayer, item: ItemStack)
def place(world:World, player:EntityPlayer, item:ItemStack) def consume(world: World, player: EntityPlayer, item: ItemStack)
def consume(world:World, player:EntityPlayer, item:ItemStack)
} }
class AdditionPlacement($pos:BlockCoord, $part:Microblock) extends ExecutablePlacement($pos, $part) class AdditionPlacement($pos: BlockCoord, $part: Microblock)
{ extends ExecutablePlacement($pos, $part) {
def place(world:World, player:EntityPlayer, item:ItemStack) def place(world: World, player: EntityPlayer, item: ItemStack) {
{ TileMultipart.addPart(world, pos, part)
TileMultipart.addPart(world, pos, part) }
def consume(world: World, player: EntityPlayer, item: ItemStack) {
item.stackSize -= 1
}
}
class ExpandingPlacement($pos: BlockCoord, $part: Microblock, opart: Microblock)
extends ExecutablePlacement($pos, $part) {
def place(world: World, player: EntityPlayer, item: ItemStack) {
opart.shape = part.shape
opart.tile.notifyPartChange(opart)
opart.sendShapeUpdate()
}
def consume(world: World, player: EntityPlayer, item: ItemStack) {
item.stackSize -= 1
}
}
abstract class PlacementProperties {
def opposite(slot: Int, side: Int): Int
def sneakOpposite(slot: Int, side: Int) = true
def expand(slot: Int, side: Int) = true
def microClass: MicroblockClass
def placementGrid: PlacementGrid
def customPlacement(pmt: MicroblockPlacement): ExecutablePlacement = null
}
object MicroblockPlacement {
def apply(
player: EntityPlayer,
hit: MovingObjectPosition,
size: Int,
material: Int,
checkMaterial: Boolean,
pp: PlacementProperties
): ExecutablePlacement =
new MicroblockPlacement(player, hit, size, material, checkMaterial, pp)()
}
class MicroblockPlacement(
val player: EntityPlayer,
val hit: MovingObjectPosition,
val size: Int,
val material: Int,
val checkMaterial: Boolean,
val pp: PlacementProperties
) {
val world = player.worldObj
val mcrClass = pp.microClass
val pos = new BlockCoord(hit.blockX, hit.blockY, hit.blockZ)
val vhit = new Vector3(hit.hitVec).add(-pos.x, -pos.y, -pos.z)
val gtile = TileMultipart.getOrConvertTile2(world, pos)
val htile = gtile._1
val slot = pp.placementGrid.getHitSlot(vhit, hit.sideHit)
val oslot = pp.opposite(slot, hit.sideHit)
val d = getHitDepth(vhit, hit.sideHit)
val useOppMod = pp.sneakOpposite(slot, hit.sideHit)
val oppMod = player.isControlDown
val internal = d < 1 && htile != null
val doExpand =
internal && !gtile._2 && !player.isSneaking && !(oppMod && useOppMod) && pp
.expand(slot, hit.sideHit)
val side = hit.sideHit
def apply(): ExecutablePlacement = {
val customPlacement = pp.customPlacement(this)
if (customPlacement != null)
return customPlacement
if (slot < 0)
return null
if (doExpand) {
val hpart = htile.partList(ExtendedMOP.getData[(Int, _)](hit)._1)
if (hpart.getType == mcrClass.getName) {
val mpart = hpart.asInstanceOf[CommonMicroblock]
if (mpart.material == material && mpart.getSize + size < 8)
return expand(mpart)
}
} }
def consume(world:World, player:EntityPlayer, item:ItemStack) if (internal) {
{ if (d < 0.5 || !useOppMod) {
item.stackSize-=1 val ret = internalPlacement(htile, slot)
} if (ret != null) {
} if (!useOppMod || !oppMod) return ret
else return internalPlacement(htile, oslot)
class ExpandingPlacement($pos:BlockCoord, $part:Microblock, opart:Microblock) extends ExecutablePlacement($pos, $part)
{
def place(world:World, player:EntityPlayer, item:ItemStack)
{
opart.shape = part.shape
opart.tile.notifyPartChange(opart)
opart.sendShapeUpdate()
}
def consume(world:World, player:EntityPlayer, item:ItemStack)
{
item.stackSize-=1
}
}
abstract class PlacementProperties
{
def opposite(slot:Int, side:Int):Int
def sneakOpposite(slot:Int, side:Int) = true
def expand(slot:Int, side:Int) = true
def microClass:MicroblockClass
def placementGrid:PlacementGrid
def customPlacement(pmt:MicroblockPlacement):ExecutablePlacement = null
}
object MicroblockPlacement
{
def apply(player:EntityPlayer, hit:MovingObjectPosition, size:Int, material:Int, checkMaterial:Boolean, pp:PlacementProperties):ExecutablePlacement =
new MicroblockPlacement(player, hit, size, material, checkMaterial, pp)()
}
class MicroblockPlacement(val player:EntityPlayer, val hit:MovingObjectPosition, val size:Int, val material:Int, val checkMaterial:Boolean, val pp:PlacementProperties)
{
val world = player.worldObj
val mcrClass = pp.microClass
val pos = new BlockCoord(hit.blockX, hit.blockY, hit.blockZ)
val vhit = new Vector3(hit.hitVec).add(-pos.x, -pos.y, -pos.z)
val gtile = TileMultipart.getOrConvertTile2(world, pos)
val htile = gtile._1
val slot = pp.placementGrid.getHitSlot(vhit, hit.sideHit)
val oslot = pp.opposite(slot, hit.sideHit)
val d = getHitDepth(vhit, hit.sideHit)
val useOppMod = pp.sneakOpposite(slot, hit.sideHit)
val oppMod = player.isControlDown
val internal = d < 1 && htile != null
val doExpand = internal && !gtile._2 && !player.isSneaking && !(oppMod && useOppMod) && pp.expand(slot, hit.sideHit)
val side = hit.sideHit
def apply():ExecutablePlacement =
{
val customPlacement = pp.customPlacement(this)
if(customPlacement != null)
return customPlacement
if(slot < 0)
return null
if(doExpand)
{
val hpart = htile.partList(ExtendedMOP.getData[(Int, _)](hit)._1)
if(hpart.getType == mcrClass.getName)
{
val mpart = hpart.asInstanceOf[CommonMicroblock]
if(mpart.material == material && mpart.getSize + size < 8)
return expand(mpart)
}
} }
}
if(internal) if (useOppMod && !oppMod)
{ return internalPlacement(htile, oslot)
if(d < 0.5 || !useOppMod) else
{ return externalPlacement(slot)
val ret = internalPlacement(htile, slot)
if(ret != null) {
if(!useOppMod || !oppMod) return ret
else return internalPlacement(htile, oslot)
}
}
if(useOppMod && !oppMod)
return internalPlacement(htile, oslot)
else
return externalPlacement(slot)
}
if(!useOppMod || !oppMod)
return externalPlacement(slot)
else
return externalPlacement(oslot)
} }
def expand(mpart:CommonMicroblock):ExecutablePlacement = expand(mpart, create(mpart.getSize+size, mpart.getSlot, mpart.material)) if (!useOppMod || !oppMod)
return externalPlacement(slot)
else
return externalPlacement(oslot)
}
def expand(mpart:Microblock, npart:Microblock):ExecutablePlacement = def expand(mpart: CommonMicroblock): ExecutablePlacement =
{ expand(mpart, create(mpart.getSize + size, mpart.getSlot, mpart.material))
val pos = new BlockCoord(mpart.tile)
if(TileMultipart.checkNoEntityCollision(world, pos, npart) && mpart.tile.canReplacePart(mpart, npart))
return new ExpandingPlacement(pos, npart, mpart)
return null
}
def internalPlacement(htile:TileMultipart, slot:Int):ExecutablePlacement = internalPlacement(htile, create(size, slot, material)) def expand(mpart: Microblock, npart: Microblock): ExecutablePlacement = {
val pos = new BlockCoord(mpart.tile)
if (
TileMultipart.checkNoEntityCollision(world, pos, npart) && mpart.tile
.canReplacePart(mpart, npart)
)
return new ExpandingPlacement(pos, npart, mpart)
return null
}
def internalPlacement(htile:TileMultipart, npart:Microblock):ExecutablePlacement = def internalPlacement(htile: TileMultipart, slot: Int): ExecutablePlacement =
{ internalPlacement(htile, create(size, slot, material))
val pos = new BlockCoord(htile)
if(TileMultipart.checkNoEntityCollision(world, pos, npart) && htile.canAddPart(npart))
return new AdditionPlacement(pos, npart)
return null
}
def externalPlacement(slot:Int):ExecutablePlacement = externalPlacement(create(size, slot, material)) def internalPlacement(
htile: TileMultipart,
npart: Microblock
): ExecutablePlacement = {
val pos = new BlockCoord(htile)
if (
TileMultipart.checkNoEntityCollision(world, pos, npart) && htile
.canAddPart(npart)
)
return new AdditionPlacement(pos, npart)
return null
}
def externalPlacement(npart:Microblock):ExecutablePlacement = def externalPlacement(slot: Int): ExecutablePlacement = externalPlacement(
{ create(size, slot, material)
val pos = this.pos.copy().offset(side) )
if(TileMultipart.canPlacePart(world, pos, npart))
return new AdditionPlacement(pos, npart)
return null
}
def getHitDepth(vhit:Vector3, side:Int):Double = def externalPlacement(npart: Microblock): ExecutablePlacement = {
vhit.copy.scalarProject(Rotation.axes(side)) + (side%2^1) val pos = this.pos.copy().offset(side)
if (TileMultipart.canPlacePart(world, pos, npart))
return new AdditionPlacement(pos, npart)
return null
}
def create(size:Int, slot:Int, material:Int) = { def getHitDepth(vhit: Vector3, side: Int): Double =
val part = mcrClass.create(world.isRemote, material) vhit.copy.scalarProject(Rotation.axes(side)) + (side % 2 ^ 1)
part.setShape(size, slot)
part def create(size: Int, slot: Int, material: Int) = {
} val part = mcrClass.create(world.isRemote, material)
part.setShape(size, slot)
part
}
} }
@@ -7,49 +7,70 @@ import org.lwjgl.opengl.GL11._
import codechicken.lib.render.{CCRenderState, TextureUtils} import codechicken.lib.render.{CCRenderState, TextureUtils}
import codechicken.lib.render.BlockRenderer.BlockFace import codechicken.lib.render.BlockRenderer.BlockFace
import codechicken.microblock.MicroMaterialRegistry.IMicroMaterial import codechicken.microblock.MicroMaterialRegistry.IMicroMaterial
import java.util.function.Supplier
object MicroblockRender object MicroblockRender {
{ def renderHighlight(
def renderHighlight(player:EntityPlayer, hit:MovingObjectPosition, mcrClass:CommonMicroClass, size:Int, material:Int) player: EntityPlayer,
{ hit: MovingObjectPosition,
mcrClass.placementProperties.placementGrid.render(new Vector3(hit.hitVec), hit.sideHit) mcrClass: CommonMicroClass,
size: Int,
material: Int
) {
mcrClass.placementProperties.placementGrid
.render(new Vector3(hit.hitVec), hit.sideHit)
val placement = MicroblockPlacement(player, hit, size, material, !player.capabilities.isCreativeMode, mcrClass.placementProperties) val placement = MicroblockPlacement(
if(placement == null) player,
return hit,
val pos = placement.pos size,
val part = placement.part.asInstanceOf[MicroblockClient] material,
!player.capabilities.isCreativeMode,
mcrClass.placementProperties
)
if (placement == null)
return
val pos = placement.pos
val part = placement.part.asInstanceOf[MicroblockClient]
val state = CCRenderState.instance
glPushMatrix() glPushMatrix()
glTranslated(pos.x+0.5, pos.y+0.5, pos.z+0.5) glTranslated(pos.x + 0.5, pos.y + 0.5, pos.z + 0.5)
glScaled(1.002, 1.002, 1.002) glScaled(1.002, 1.002, 1.002)
glTranslated(-0.5, -0.5, -0.5) glTranslated(-0.5, -0.5, -0.5)
glEnable(GL_BLEND) glEnable(GL_BLEND)
glDepthMask(false) glDepthMask(false)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
// TODO: update to use a thread local copy
TextureUtils.bindAtlas(0)
state.resetInstance()
state.alphaOverride = 80
state.useNormals = true
state.startDrawingInstance()
part.render(Vector3.zero, -1)
state.drawInstance()
TextureUtils.bindAtlas(0) glDisable(GL_BLEND)
CCRenderState.reset() glDepthMask(true)
CCRenderState.alphaOverride = 80 glPopMatrix()
CCRenderState.useNormals = true }
CCRenderState.startDrawing()
part.render(Vector3.zero, -1)
CCRenderState.draw()
glDisable(GL_BLEND) val face = ThreadLocal.withInitial[BlockFace](new Supplier[BlockFace]() {
glDepthMask(true) override def get(): BlockFace = new BlockFace()
glPopMatrix() })
} def renderCuboid(
pos: Vector3,
val face = new BlockFace() mat: IMicroMaterial,
def renderCuboid(pos:Vector3, mat:IMicroMaterial, pass:Int, c:Cuboid6, faces:Int) { pass: Int,
CCRenderState.setModel(face) c: Cuboid6,
for(s <- 0 until 6 if (faces & 1<<s) == 0) { faces: Int
face.loadCuboidFace(c, s) ) {
mat.renderMicroFace(pos, pass, c) val localFace = face.get()
} CCRenderState.instance().setModelInstance(localFace)
for (s <- 0 until 6 if (faces & 1 << s) == 0) {
localFace.loadCuboidFace(c, s)
mat.renderMicroFace(pos, pass, c)
} }
}
} }
@@ -0,0 +1,55 @@
package codechicken.microblock
import codechicken.lib.render.uv.IconTransformation
import codechicken.lib.vec.{Cuboid6, Vector3}
import codechicken.microblock.MicroMaterialRegistry.IMicroMaterial
import codechicken.microblock.handler.MicroblockProxy
import cpw.mods.fml.relauncher.{Side, SideOnly}
import net.minecraft.block.Block
import net.minecraft.block.Block.SoundType
import net.minecraft.entity.Entity
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.init.Blocks
import net.minecraft.item.ItemStack
import net.minecraft.util.IIcon
/** Stand-in for a material whose name could not be resolved at load time.
* Renders the vanilla missing texture (magenta/black checkerboard) and behaves
* inertly. Resolving an unknown name to this placeholder keeps microblocks
* from silently becoming material id 0 (Blood Rune in GTNH).
*/
object MissingMicroMaterial extends IMicroMaterial {
val key = "forgemicroblock:missing"
@SideOnly(Side.CLIENT)
private var icon: IIcon = _
@SideOnly(Side.CLIENT)
override def loadIcons(): Unit = {
icon = MicroblockProxy.renderBlocks.getIconSafe(null)
}
@SideOnly(Side.CLIENT)
override def getBreakingIcon(side: Int): IIcon = icon
@SideOnly(Side.CLIENT)
override def renderMicroFace(
pos: Vector3,
pass: Int,
bounds: Cuboid6
): Unit = {
MaterialRenderHelper
.start(pos, pass, new IconTransformation(icon))
.lighting()
.render()
}
override def isTransparent: Boolean = false
override def getLightValue: Int = 0
override def getStrength(player: EntityPlayer): Float = 1f
override def getLocalizedName: String = "Missing Material"
override def getItem: ItemStack = new ItemStack(Blocks.stone)
override def getCutterStrength: Int = 0
override def getSound: SoundType = Block.soundTypeStone
override def explosionResistance(entity: Entity): Float = 6f
}
@@ -7,173 +7,174 @@ import Rotation._
import org.lwjgl.opengl.GL11._ import org.lwjgl.opengl.GL11._
import codechicken.multipart.PartMap import codechicken.multipart.PartMap
trait PlacementGrid trait PlacementGrid {
{ def getHitSlot(vhit: Vector3, side: Int): Int
def getHitSlot(vhit: Vector3, side: Int): Int
def render(hit: Vector3, side: Int) { def render(hit: Vector3, side: Int) {
glTransformFace(hit, side) glTransformFace(hit, side)
glLineWidth(2) glLineWidth(2)
glColor4f(0, 0, 0, 1) glColor4f(0, 0, 0, 1)
glBegin(GL_LINES) glBegin(GL_LINES)
drawLines() drawLines()
glEnd() glEnd()
glPopMatrix() glPopMatrix()
} }
def drawLines() {} def drawLines() {}
def glTransformFace(hit: Vector3, side: Int) { def glTransformFace(hit: Vector3, side: Int) {
val pos = new BlockCoord(hit) val pos = new BlockCoord(hit)
glPushMatrix() glPushMatrix()
glTranslated(pos.x + 0.5, pos.y + 0.5, pos.z + 0.5) glTranslated(pos.x + 0.5, pos.y + 0.5, pos.z + 0.5)
sideRotations(side).glApply() sideRotations(side).glApply()
val rhit = new Vector3(pos.x + 0.5, pos.y + 0.5, pos.z + 0.5).subtract(hit).apply(sideRotations(side ^ 1).inverse) val rhit = new Vector3(pos.x + 0.5, pos.y + 0.5, pos.z + 0.5)
glTranslated(0, rhit.y - 0.002, 0) .subtract(hit)
} .apply(sideRotations(side ^ 1).inverse)
glTranslated(0, rhit.y - 0.002, 0)
}
} }
class FaceEdgeGrid(size: Double) extends PlacementGrid class FaceEdgeGrid(size: Double) extends PlacementGrid {
{ override def drawLines() {
override def drawLines() { glVertex3d(-0.5, 0, -0.5)
glVertex3d(-0.5, 0, -0.5) glVertex3d(-0.5, 0, 0.5)
glVertex3d(-0.5, 0, 0.5)
glVertex3d(-0.5, 0, 0.5) glVertex3d(-0.5, 0, 0.5)
glVertex3d(0.5, 0, 0.5) glVertex3d(0.5, 0, 0.5)
glVertex3d(0.5, 0, 0.5) glVertex3d(0.5, 0, 0.5)
glVertex3d(0.5, 0, -0.5) glVertex3d(0.5, 0, -0.5)
glVertex3d(0.5, 0, -0.5) glVertex3d(0.5, 0, -0.5)
glVertex3d(-0.5, 0, -0.5) glVertex3d(-0.5, 0, -0.5)
glVertex3d(0.5, 0, 0.5) glVertex3d(0.5, 0, 0.5)
glVertex3d(size, 0, size) glVertex3d(size, 0, size)
glVertex3d(-0.5, 0, 0.5) glVertex3d(-0.5, 0, 0.5)
glVertex3d(-size, 0, size) glVertex3d(-size, 0, size)
glVertex3d(0.5, 0, -0.5) glVertex3d(0.5, 0, -0.5)
glVertex3d(size, 0, -size) glVertex3d(size, 0, -size)
glVertex3d(-0.5, 0, -0.5) glVertex3d(-0.5, 0, -0.5)
glVertex3d(-size, 0, -size) glVertex3d(-size, 0, -size)
glVertex3d(-size, 0, -size) glVertex3d(-size, 0, -size)
glVertex3d(-size, 0, size) glVertex3d(-size, 0, size)
glVertex3d(-size, 0, size) glVertex3d(-size, 0, size)
glVertex3d(size, 0, size) glVertex3d(size, 0, size)
glVertex3d(size, 0, size) glVertex3d(size, 0, size)
glVertex3d(size, 0, -size) glVertex3d(size, 0, -size)
glVertex3d(size, 0, -size) glVertex3d(size, 0, -size)
glVertex3d(-size, 0, -size) glVertex3d(-size, 0, -size)
} }
def getHitSlot(vhit: Vector3, side: Int) = { def getHitSlot(vhit: Vector3, side: Int) = {
val s1 = (side + 2) % 6 val s1 = (side + 2) % 6
val s2 = (side + 4) % 6 val s2 = (side + 4) % 6
val u = vhit.copy.add(-0.5, -0.5, -0.5).scalarProject(Rotation.axes(s1)) val u = vhit.copy.add(-0.5, -0.5, -0.5).scalarProject(Rotation.axes(s1))
val v = vhit.copy.add(-0.5, -0.5, -0.5).scalarProject(Rotation.axes(s2)) val v = vhit.copy.add(-0.5, -0.5, -0.5).scalarProject(Rotation.axes(s2))
if (Math.abs(u) < size && Math.abs(v) < size) if (Math.abs(u) < size && Math.abs(v) < size)
side ^ 1 side ^ 1
else if (Math.abs(u) > Math.abs(v)) else if (Math.abs(u) > Math.abs(v))
if (u > 0) s1 else s1 ^ 1 if (u > 0) s1 else s1 ^ 1
else else if (v > 0) s2
if (v > 0) s2 else s2 ^ 1 else s2 ^ 1
} }
} }
object FacePlacementGrid extends FaceEdgeGrid(1 / 4D) object FacePlacementGrid extends FaceEdgeGrid(1 / 4d)
object CornerPlacementGrid extends PlacementGrid object CornerPlacementGrid extends PlacementGrid {
{ override def drawLines() {
override def drawLines() { glVertex3d(-0.5, 0, -0.5)
glVertex3d(-0.5, 0, -0.5) glVertex3d(-0.5, 0, 0.5)
glVertex3d(-0.5, 0, 0.5)
glVertex3d(-0.5, 0, 0.5) glVertex3d(-0.5, 0, 0.5)
glVertex3d(0.5, 0, 0.5) glVertex3d(0.5, 0, 0.5)
glVertex3d(0.5, 0, 0.5) glVertex3d(0.5, 0, 0.5)
glVertex3d(0.5, 0, -0.5) glVertex3d(0.5, 0, -0.5)
glVertex3d(0.5, 0, -0.5) glVertex3d(0.5, 0, -0.5)
glVertex3d(-0.5, 0, -0.5) glVertex3d(-0.5, 0, -0.5)
glVertex3d(0, 0, -0.5) glVertex3d(0, 0, -0.5)
glVertex3d(0, 0, 0.5) glVertex3d(0, 0, 0.5)
glVertex3d(-0.5, 0, 0) glVertex3d(-0.5, 0, 0)
glVertex3d(0.5, 0, 0) glVertex3d(0.5, 0, 0)
} }
def getHitSlot(vhit: Vector3, side: Int): Int = { def getHitSlot(vhit: Vector3, side: Int): Int = {
val s1 = ((side & 6) + 3) % 6 val s1 = ((side & 6) + 3) % 6
val s2 = ((side & 6) + 5) % 6 val s2 = ((side & 6) + 5) % 6
val u = vhit.copy().add(-0.5, -0.5, -0.5).scalarProject(Rotation.axes(s1)) val u = vhit.copy().add(-0.5, -0.5, -0.5).scalarProject(Rotation.axes(s1))
val v = vhit.copy().add(-0.5, -0.5, -0.5).scalarProject(Rotation.axes(s2)) val v = vhit.copy().add(-0.5, -0.5, -0.5).scalarProject(Rotation.axes(s2))
val bu = if (u >= 0) 1 else 0 val bu = if (u >= 0) 1 else 0
val bv = if (v >= 0) 1 else 0 val bv = if (v >= 0) 1 else 0
val bw = (side & 1) ^ 1 val bw = (side & 1) ^ 1
return 7 + ( return 7 + (bw << (side >> 1) |
bw << (side >> 1) | bu << (s1 >> 1) |
bu << (s1 >> 1) | bv << (s2 >> 1))
bv << (s2 >> 1)) }
}
} }
object EdgePlacementGrid extends PlacementGrid object EdgePlacementGrid extends PlacementGrid {
{ override def drawLines() {
override def drawLines() { glVertex3d(-0.5, 0, -0.5)
glVertex3d(-0.5, 0, -0.5) glVertex3d(-0.5, 0, 0.5)
glVertex3d(-0.5, 0, 0.5)
glVertex3d(-0.5, 0, 0.5) glVertex3d(-0.5, 0, 0.5)
glVertex3d(0.5, 0, 0.5) glVertex3d(0.5, 0, 0.5)
glVertex3d(0.5, 0, 0.5) glVertex3d(0.5, 0, 0.5)
glVertex3d(0.5, 0, -0.5) glVertex3d(0.5, 0, -0.5)
glVertex3d(0.5, 0, -0.5) glVertex3d(0.5, 0, -0.5)
glVertex3d(-0.5, 0, -0.5) glVertex3d(-0.5, 0, -0.5)
glVertex3d(0.25, 0, -0.5) glVertex3d(0.25, 0, -0.5)
glVertex3d(0.25, 0, 0.5) glVertex3d(0.25, 0, 0.5)
glVertex3d(-0.25, 0, -0.5) glVertex3d(-0.25, 0, -0.5)
glVertex3d(-0.25, 0, 0.5) glVertex3d(-0.25, 0, 0.5)
glVertex3d(-0.5, 0, 0.25) glVertex3d(-0.5, 0, 0.25)
glVertex3d(0.5, 0, 0.25) glVertex3d(0.5, 0, 0.25)
glVertex3d(-0.5, 0, -0.25) glVertex3d(-0.5, 0, -0.25)
glVertex3d(0.5, 0, -0.25) glVertex3d(0.5, 0, -0.25)
} }
override def getHitSlot(vhit: Vector3, side: Int): Int = { override def getHitSlot(vhit: Vector3, side: Int): Int = {
val s1 = (side + 2) % 6 val s1 = (side + 2) % 6
val s2 = (side + 4) % 6 val s2 = (side + 4) % 6
val u = vhit.copy.add(-0.5, -0.5, -0.5).scalarProject(Rotation.axes(s1)) val u = vhit.copy.add(-0.5, -0.5, -0.5).scalarProject(Rotation.axes(s1))
val v = vhit.copy.add(-0.5, -0.5, -0.5).scalarProject(Rotation.axes(s2)) val v = vhit.copy.add(-0.5, -0.5, -0.5).scalarProject(Rotation.axes(s2))
if (Math.abs(u) < 4 / 16D && Math.abs(v) < 4 / 16D) if (Math.abs(u) < 4 / 16d && Math.abs(v) < 4 / 16d)
return -1 return -1
if(Math.abs(u) > 4 / 16D && Math.abs(v) > 4 / 16D) if (Math.abs(u) > 4 / 16d && Math.abs(v) > 4 / 16d)
return PartMap.edgeBetween(if(u > 0) s1 else s1^1, if(v > 0) s2 else s2^1) return PartMap.edgeBetween(
if (u > 0) s1 else s1 ^ 1,
if (v > 0) s2 else s2 ^ 1
)
val s = if(Math.abs(u) > Math.abs(v)) val s =
if(u > 0) s1 else s1^1 if (Math.abs(u) > Math.abs(v))
else if (u > 0) s1 else s1 ^ 1
if(v > 0) s2 else s2^1 else if (v > 0) s2
else s2 ^ 1
return PartMap.edgeBetween(side^1, s) return PartMap.edgeBetween(side ^ 1, s)
} }
} }
@@ -5,257 +5,249 @@ import codechicken.lib.vec.Cuboid6
import codechicken.multipart.PartMap._ import codechicken.multipart.PartMap._
import codechicken.lib.data.MCDataInput import codechicken.lib.data.MCDataInput
/** /** Suite of classes for performing microblock style occlusion and shrink
* Suite of classes for performing microblock style occlusion and shrink rendering. Use at your own peril. * rendering. Use at your own peril.
*/ */
object MicroOcclusion object MicroOcclusion {
{ def shrink(renderBounds: Cuboid6, b: Cuboid6, side: Int) = side match {
def shrink(renderBounds:Cuboid6, b:Cuboid6, side:Int) = side match case -1 =>
case 0 => if (renderBounds.min.y < b.max.y) renderBounds.min.y = b.max.y
case 1 => if (renderBounds.max.y > b.min.y) renderBounds.max.y = b.min.y
case 2 => if (renderBounds.min.z < b.max.z) renderBounds.min.z = b.max.z
case 3 => if (renderBounds.max.z > b.min.z) renderBounds.max.z = b.min.z
case 4 => if (renderBounds.min.x < b.max.x) renderBounds.min.x = b.max.x
case 5 => if (renderBounds.max.x > b.min.x) renderBounds.max.x = b.min.x
}
def shrinkFrom(
p: JMicroShrinkRender,
other: JMicroShrinkRender,
renderBounds: Cuboid6
): Int = {
if (shrinkTest(p, other)) {
shrink(
renderBounds,
other.getBounds,
shrinkSide(p.getSlot, other.getSlot)
)
} else if (
other.getSlot < 6 && !other.isTransparent
) // other gets full face, we didn't shrink, flag rendermask
{
if (
other.getSlot match {
case 0 => renderBounds.min.y <= 0
case 1 => renderBounds.max.y >= 1
case 2 => renderBounds.min.z <= 0
case 3 => renderBounds.max.z >= 1
case 4 => renderBounds.min.x <= 0
case 5 => renderBounds.max.x >= 1
}
)
return 1 << other.getSlot
}
return 0
}
def shrink(p: JMicroShrinkRender, renderBounds: Cuboid6, m: Int): Int = {
var renderMask = 0
val part = p.asInstanceOf[TMultiPart]
val tile = part.tile
for (i <- 0 until m)
if (i != p.getSlot)
tile.partMap(i) match {
case other: JMicroShrinkRender =>
renderMask |= shrinkFrom(p, other, renderBounds)
case _ =>
}
return renderMask
}
def shrinkSide(s1: Int, s2: Int): Int = {
if (s2 < 6) // other is a cover
return s2
if (s1 < 15) // both corners
{
val c1 = s1 - 7
val c2 = s2 - 7
return c1 ^ c2 match // different axis bits will become 1, same 0
{
case 1 => c2 & 1
case 2 => 2 | (c2 & 2) >> 1
case 4 => 4 | (c2 & 4) >> 2
case _ => -1
}
}
if (s2 < 15) // edge, other corner
{
val e1 = s1 - 15
val c2 = s2 - 7
val ebits = unpackEdgeBits(e1)
if ((c2 & edgeAxisMask(e1)) != ebits)
return -1
return (e1 & 0xc) >> 1 | (c2 & (~ebits)) >> (e1 >> 2)
}
// both edges
{ {
case -1 => val e1 = s1 - 15
case 0 => if(renderBounds.min.y < b.max.y)renderBounds.min.y = b.max.y val e2 = s2 - 15
case 1 => if(renderBounds.max.y > b.min.y)renderBounds.max.y = b.min.y val e1bits = unpackEdgeBits(e1)
case 2 => if(renderBounds.min.z < b.max.z)renderBounds.min.z = b.max.z val e2bits = unpackEdgeBits(e2)
case 3 => if(renderBounds.max.z > b.min.z)renderBounds.max.z = b.min.z if ((e1 & 0xc) == (e2 & 0xc)) // same axis
case 4 => if(renderBounds.min.x < b.max.x)renderBounds.min.x = b.max.x {
case 5 => if(renderBounds.max.x > b.min.x)renderBounds.max.x = b.min.x return e1bits ^ e2bits match {
case 1 => if ((e2bits & 1) == 0) 0 else 1
case 2 => if ((e2bits & 2) == 0) 2 else 3
case 4 => if ((e2bits & 4) == 0) 4 else 5
case _ => -1
}
} else {
val mask = edgeAxisMask(e1) & edgeAxisMask(e2)
if ((e1bits & mask) != (e2bits & mask))
return -1
return e1 >> 2 match {
case 0 => if ((e2bits & 1) == 0) 0 else 1
case 1 => if ((e2bits & 2) == 0) 2 else 3
case 2 => if ((e2bits & 4) == 0) 4 else 5
}
}
} }
def shrinkFrom(p:JMicroShrinkRender, other:JMicroShrinkRender, renderBounds:Cuboid6):Int = throw new IllegalArgumentException("Switch Falloff")
{ }
if(shrinkTest(p, other))
{ def recalcBounds(p: JMicroShrinkRender, renderBounds: Cuboid6) = {
shrink(renderBounds, other.getBounds, shrinkSide(p.getSlot, other.getSlot)) if (p.getSlot < 6)
} shrink(p, renderBounds, 6)
else if(other.getSlot < 6 && !other.isTransparent)//other gets full face, we didn't shrink, flag rendermask else if (p.getSlot < 15)
{ shrink(p, renderBounds, 15)
if(other.getSlot match { else
case 0 => renderBounds.min.y <= 0 shrink(p, renderBounds, 27)
case 1 => renderBounds.max.y >= 1 }
case 2 => renderBounds.min.z <= 0
case 3 => renderBounds.max.z >= 1 def shapePriority(slot: Int): Int =
case 4 => renderBounds.min.x <= 0 if (slot < 6)
case 5 => renderBounds.max.x >= 1 return 2
}) else if (slot < 15)
return 1<<other.getSlot return 1
} else
return 0 return 0
}
def shrinkTest(a: JMicroShrinkRender, b: JMicroShrinkRender): Boolean = {
def shrink(p:JMicroShrinkRender, renderBounds:Cuboid6, m:Int):Int = if (a.getPriorityClass != b.getPriorityClass)
{ return a.getPriorityClass < b.getPriorityClass
var renderMask = 0
val part = p.asInstanceOf[TMultiPart] val shape1 = shapePriority(a.getSlot)
val tile = part.tile val shape2 = shapePriority(b.getSlot)
for(i <- 0 until m)
if(i != p.getSlot) if (shape1 != shape2) return shape1 < shape2
tile.partMap(i) match { if (a.getSlot < 6) // transparency takes precedence for covers
case other:JMicroShrinkRender => {
renderMask |= shrinkFrom(p, other, renderBounds) if (a.isTransparent != b.isTransparent) return a.isTransparent
case _ => if (a.getSize != b.getSize) return a.getSize < b.getSize
} } else {
return renderMask if (a.getSize != b.getSize) return a.getSize < b.getSize
} if (a.isTransparent != b.isTransparent) return a.isTransparent
def shrinkSide(s1:Int, s2:Int):Int = {
if(s2 < 6)//other is a cover
return s2
if(s1 < 15)//both corners
{
val c1 = s1-7
val c2 = s2-7
return c1^c2 match//different axis bits will become 1, same 0
{
case 1 => c2&1
case 2 => 2|(c2&2)>>1
case 4 => 4|(c2&4)>>2
case _ => -1
}
}
if(s2 < 15)//edge, other corner
{
val e1 = s1-15
val c2 = s2-7
val ebits = unpackEdgeBits(e1)
if((c2&edgeAxisMask(e1)) != ebits)
return -1
return (e1&0xC)>>1|(c2&(~ebits))>>(e1>>2)
}
//both edges
{
val e1 = s1-15
val e2 = s2-15
val e1bits = unpackEdgeBits(e1)
val e2bits = unpackEdgeBits(e2)
if((e1&0xC) == (e2&0xC))//same axis
{
return e1bits^e2bits match
{
case 1 => if((e2bits&1) == 0) 0 else 1
case 2 => if((e2bits&2) == 0) 2 else 3
case 4 => if((e2bits&4) == 0) 4 else 5
case _ => -1
}
}
else
{
val mask = edgeAxisMask(e1)&edgeAxisMask(e2)
if((e1bits&mask) != (e2bits&mask))
return -1
return e1>>2 match
{
case 0 => if((e2bits&1) == 0) 0 else 1
case 1 => if((e2bits&2) == 0) 2 else 3
case 2 => if((e2bits&4) == 0) 4 else 5
}
}
}
throw new IllegalArgumentException("Switch Falloff")
}
def recalcBounds(p:JMicroShrinkRender, renderBounds:Cuboid6) =
{
if(p.getSlot < 6)
shrink(p, renderBounds, 6)
else if(p.getSlot < 15)
shrink(p, renderBounds, 15)
else
shrink(p, renderBounds, 27)
}
def shapePriority(slot:Int):Int =
if(slot < 6)
return 2
else if(slot < 15)
return 1
else
return 0
def shrinkTest(a:JMicroShrinkRender, b:JMicroShrinkRender):Boolean =
{
if(a.getPriorityClass != b.getPriorityClass) return a.getPriorityClass < b.getPriorityClass
val shape1 = shapePriority(a.getSlot)
val shape2 = shapePriority(b.getSlot)
if(shape1 != shape2) return shape1 < shape2
if(a.getSlot < 6)//transparency takes precedence for covers
{
if(a.isTransparent != b.isTransparent) return a.isTransparent
if(a.getSize != b.getSize) return a.getSize < b.getSize
}
else
{
if(a.getSize != b.getSize) return a.getSize < b.getSize
if(a.isTransparent != b.isTransparent) return a.isTransparent
}
return a.getSlot < b.getSlot
} }
return a.getSlot < b.getSlot
}
} }
trait JMicroShrinkRender trait JMicroShrinkRender {
{ def getPriorityClass: Int
def getPriorityClass:Int def getSlot: Int
def getSlot:Int def getSize: Int
def getSize:Int def isTransparent: Boolean
def isTransparent:Boolean def getBounds: Cuboid6
def getBounds:Cuboid6
} }
trait TMicroOcclusionClient extends TMicroOcclusion with JMicroShrinkRender trait TMicroOcclusionClient extends TMicroOcclusion with JMicroShrinkRender {
{ var renderBounds: Cuboid6 = _
var renderBounds:Cuboid6 = _ var renderMask: Int = _
var renderMask:Int = _
override def onPartChanged(part:TMultiPart) override def onPartChanged(part: TMultiPart) {
{ super.onPartChanged(part)
super.onPartChanged(part) recalcBounds()
recalcBounds() }
}
override def onAdded() override def onAdded() {
{ super.onAdded()
super.onAdded() recalcBounds()
recalcBounds() }
}
override def read(packet:MCDataInput) override def read(packet: MCDataInput) {
{ super.read(packet)
super.read(packet) recalcBounds()
recalcBounds() }
}
def recalcBounds() def recalcBounds() {
{ renderBounds = getBounds.copy
renderBounds = getBounds.copy renderMask = MicroOcclusion.recalcBounds(this, renderBounds)
renderMask = MicroOcclusion.recalcBounds(this, renderBounds) }
}
override def getPriorityClass = 0 override def getPriorityClass = 0
} }
trait TMicroOcclusion extends TMultiPart trait TMicroOcclusion extends TMultiPart {
{ import MicroOcclusion._
import MicroOcclusion._
def getSlot:Int def getSlot: Int
def getSize:Int def getSize: Int
def getMaterial:Int def getMaterial: Int
def getBounds:Cuboid6 def getBounds: Cuboid6
override def occlusionTest(npart:TMultiPart):Boolean = override def occlusionTest(npart: TMultiPart): Boolean = {
{ if (!super.occlusionTest(npart))
if(!super.occlusionTest(npart)) return false
if (!npart.isInstanceOf[TMicroOcclusion])
return true
val mpart = npart.asInstanceOf[TMicroOcclusion]
val shape1 = shapePriority(getSlot)
val shape2 = shapePriority(mpart.getSlot)
if (mpart.getSize + getSize > 8) // intersecting if opposite
{
if (shape1 == 2 && shape2 == 2)
if (mpart.getSlot == (getSlot ^ 1))
return false return false
if(!npart.isInstanceOf[TMicroOcclusion]) if (mpart.getMaterial != getMaterial) {
return true if (shape1 == 1 && shape2 == 1) {
val axisMask = (getSlot - 7) ^ (mpart.getSlot - 7)
if (axisMask == 3 || axisMask == 5 || axisMask == 6)
return false
}
val mpart = npart.asInstanceOf[TMicroOcclusion] if (shape1 == 0 && shape2 == 1)
val shape1 = shapePriority(getSlot) if (!edgeCornerOcclusionTest(this, mpart))
val shape2 = shapePriority(mpart.getSlot) return false
if(mpart.getSize + getSize > 8)//intersecting if opposite if (shape1 == 1 && shape2 == 0)
{ if (!edgeCornerOcclusionTest(mpart, this))
if(shape1 == 2 && shape2 == 2) return false
if(mpart.getSlot == (getSlot^1))
return false
if(mpart.getMaterial != getMaterial) if (shape1 == 0 && shape2 == 0) {
{ val e1 = getSlot - 15
if(shape1 == 1 && shape2 == 1) val e2 = mpart.getSlot - 15
{ if ((e1 & 0xc) == (e2 & 0xc) && ((e1 & 3) ^ (e2 & 3)) == 3)
val axisMask = (getSlot-7)^(mpart.getSlot-7) return false
if(axisMask == 3 || axisMask == 5 || axisMask == 6) }
return false
}
if(shape1 == 0 && shape2 == 1)
if(!edgeCornerOcclusionTest(this, mpart))
return false
if(shape1 == 1 && shape2 == 0)
if(!edgeCornerOcclusionTest(mpart, this))
return false
if(shape1 == 0 && shape2 == 0)
{
val e1 = getSlot-15
val e2 = mpart.getSlot-15
if((e1&0xC) == (e2&0xC) && ((e1&3)^(e2&3)) == 3)
return false
}
}
} }
}
return true return true
} }
def edgeCornerOcclusionTest(edge:TMicroOcclusion, corner:TMicroOcclusion):Boolean = def edgeCornerOcclusionTest(
{ edge: TMicroOcclusion,
((corner.getSlot-7)&edgeAxisMask(edge.getSlot-15)) == unpackEdgeBits(edge.getSlot-15) corner: TMicroOcclusion
} ): Boolean = {
((corner.getSlot - 7) & edgeAxisMask(edge.getSlot - 15)) == unpackEdgeBits(
edge.getSlot - 15
)
}
} }
@@ -0,0 +1,29 @@
package codechicken.microblock.compat;
import net.minecraft.nbt.NBTTagCompound;
import com.gtnewhorizons.postea.api.IItemStackTransformationHandler;
import codechicken.microblock.MicroMaterialRegistry;
public class ItemMicroPartTransformer implements IItemStackTransformationHandler {
@Override
public boolean apply(String originalItemId, NBTTagCompound stackTag) {
if (!stackTag.hasKey("tag")) return false;
NBTTagCompound tag = stackTag.getCompoundTag("tag");
if (!tag.hasKey("mat")) return false;
String matName = tag.getString("mat");
// Goes through the remap layer, which is private
int remappedId = MicroMaterialRegistry.materialID(matName);
String remappedName = MicroMaterialRegistry.materialName(remappedId);
if (remappedName.equals(matName)) return false;
tag.setString("mat", remappedName);
stackTag.setTag("tag", tag);
return true;
}
}
@@ -0,0 +1,11 @@
package codechicken.microblock.compat;
import com.gtnewhorizons.postea.api.ItemStackReplacementManager;
public class PosteaCompat {
public static void registerTransformers() {
ItemStackReplacementManager
.addTransformationHandler("ForgeMicroblock:microblock", new ItemMicroPartTransformer());
}
}
@@ -13,28 +13,32 @@ import cpw.mods.fml.common.Loader
import cpw.mods.fml.common.LoaderState import cpw.mods.fml.common.LoaderState
import net.minecraft.util.MovingObjectPosition.MovingObjectType import net.minecraft.util.MovingObjectPosition.MovingObjectType
object MicroblockEventHandler object MicroblockEventHandler {
{ @SubscribeEvent
@SubscribeEvent @SideOnly(Side.CLIENT)
@SideOnly(Side.CLIENT) def postTextureStitch(event: TextureStitchEvent.Post) {
def postTextureStitch(event:TextureStitchEvent.Post) if (event.map.getTextureType == 0)
{ MicroMaterialRegistry.loadIcons()
if(event.map.getTextureType == 0) }
MicroMaterialRegistry.loadIcons()
}
@SubscribeEvent @SubscribeEvent
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
def drawBlockHighlight(event:DrawBlockHighlightEvent) def drawBlockHighlight(event: DrawBlockHighlightEvent) {
{ if (
if(event.currentItem != null && event.currentItem.getItem == MicroblockProxy.itemMicro && event.currentItem != null && event.currentItem.getItem == MicroblockProxy.itemMicro &&
event.target != null && event.target.typeOfHit == MovingObjectType.BLOCK) event.target != null && event.target.typeOfHit == MovingObjectType.BLOCK
{ ) {
GL11.glPushMatrix() GL11.glPushMatrix()
RenderUtils.translateToWorldCoords(event.player, event.partialTicks) RenderUtils.translateToWorldCoords(event.player, event.partialTicks)
if(ItemMicroPartRenderer.renderHighlight(event.player, event.currentItem, event.target)) if (
event.setCanceled(true) ItemMicroPartRenderer.renderHighlight(
GL11.glPopMatrix() event.player,
} event.currentItem,
event.target
)
)
event.setCanceled(true)
GL11.glPopMatrix()
} }
}
} }
@@ -5,42 +5,56 @@ import cpw.mods.fml.common.event.FMLInitializationEvent
import cpw.mods.fml.common.event.FMLPreInitializationEvent import cpw.mods.fml.common.event.FMLPreInitializationEvent
import cpw.mods.fml.common.Mod.EventHandler import cpw.mods.fml.common.Mod.EventHandler
import cpw.mods.fml.common.event.FMLServerAboutToStartEvent import cpw.mods.fml.common.event.FMLServerAboutToStartEvent
import codechicken.microblock.MicroMaterialRegistry import codechicken.microblock.{
import codechicken.microblock.DefaultContent AngelicaCompat,
ConfigContent,
DefaultContent,
MicroMaterialRegistry
}
import codechicken.multipart.Tags
import cpw.mods.fml.common.event.FMLPostInitializationEvent import cpw.mods.fml.common.event.FMLPostInitializationEvent
import codechicken.microblock.ConfigContent
import cpw.mods.fml.common.event.FMLInterModComms.IMCEvent import cpw.mods.fml.common.event.FMLInterModComms.IMCEvent
import scala.collection.JavaConversions._ import scala.collection.JavaConversions._
@Mod(modid = "ForgeMicroblock", acceptedMinecraftVersions = "[1.7.10]", dependencies = "required-after:ForgeMultipart", modLanguage = "scala") @Mod(
object MicroblockMod modid = "ForgeMicroblock",
{ name = "Forge Microblocks",
@EventHandler acceptedMinecraftVersions = "[1.7.10]",
def preInit(event: FMLPreInitializationEvent) { dependencies =
MicroblockProxy.preInit(event.getModLog) "required-after:CodeChickenCore@[1.4.3,);required-after:ForgeMultipart",
DefaultContent.load() version = Tags.VERSION,
ConfigContent.parse(event.getModConfigurationDirectory) modLanguage = "scala"
} )
object MicroblockMod {
@EventHandler
def preInit(event: FMLPreInitializationEvent) {
MicroblockProxy.preInit(event.getModLog)
DefaultContent.load()
ConfigContent.parse(event.getModConfigurationDirectory)
}
@EventHandler @EventHandler
def init(event: FMLInitializationEvent) { def init(event: FMLInitializationEvent) {
MicroblockProxy.init() MicroblockProxy.init()
ConfigContent.load() ConfigContent.load()
} }
@EventHandler @EventHandler
def postInit(event: FMLPostInitializationEvent) { def postInit(event: FMLPostInitializationEvent) {
MicroMaterialRegistry.setupIDMap() MicroMaterialRegistry.setupIDMap()
MicroblockProxy.postInit() MicroblockProxy.postInit()
} }
@EventHandler @EventHandler
def beforeServerStart(event: FMLServerAboutToStartEvent) { def beforeServerStart(event: FMLServerAboutToStartEvent) {
MicroMaterialRegistry.setupIDMap() MicroMaterialRegistry.setupIDMap()
} }
@EventHandler @EventHandler
def handleIMC(event: IMCEvent) { def handleIMC(event: IMCEvent) {
ConfigContent.handleIMC(event.getMessages) ConfigContent.handleIMC(event.getMessages)
} }
var angelicaCompat: AngelicaCompat = null
} }
@@ -1,6 +1,10 @@
package codechicken.microblock.handler package codechicken.microblock.handler
import codechicken.lib.packet.PacketCustom.{IHandshakeHandler, IClientPacketHandler, IServerPacketHandler} import codechicken.lib.packet.PacketCustom.{
IHandshakeHandler,
IClientPacketHandler,
IServerPacketHandler
}
import codechicken.lib.packet.PacketCustom import codechicken.lib.packet.PacketCustom
import net.minecraft.client.Minecraft import net.minecraft.client.Minecraft
import codechicken.microblock.MicroMaterialRegistry import codechicken.microblock.MicroMaterialRegistry
@@ -10,33 +14,59 @@ import net.minecraft.network.play.server.S40PacketDisconnect
import net.minecraft.util.ChatComponentTranslation import net.minecraft.util.ChatComponentTranslation
import net.minecraft.network.NetHandlerPlayServer import net.minecraft.network.NetHandlerPlayServer
class MicroblockPH class MicroblockPH {
{ val registryChannel =
val registryChannel = "ForgeMicroblock" //Must use the 250 system for ID registry as the NetworkMod idMap hasn't been properly initialized from the server yet. "ForgeMicroblock" // Must use the 250 system for ID registry as the NetworkMod idMap hasn't been properly initialized from the server yet.
} }
object MicroblockCPH extends MicroblockPH with IClientPacketHandler object MicroblockCPH extends MicroblockPH with IClientPacketHandler {
{ def handlePacket(
def handlePacket(packet: PacketCustom, mc: Minecraft, netHandler:INetHandlerPlayClient) { packet: PacketCustom,
packet.getType match { mc: Minecraft,
case 1 => handleMaterialRegistration(packet, netHandler) netHandler: INetHandlerPlayClient
} ) {
packet.getType match {
// In singleplayer the integrated server and this client share the one
// static registry, so the id-map packet is redundant. Skipping it avoids
// rebuilding (clearing) the shared maps on the netty thread while the
// server thread reads them - the race that turned microblocks into Blood
// Rune slabs.
case 1 =>
if (!mc.isSingleplayer)
handleMaterialRegistration(packet, netHandler)
} }
}
def handleMaterialRegistration(packet: PacketCustom, netHandler: INetHandlerPlayClient) { def handleMaterialRegistration(
val missing = MicroMaterialRegistry.readIDMap(packet) packet: PacketCustom,
if (!missing.isEmpty) netHandler: INetHandlerPlayClient
netHandler.handleDisconnect(new S40PacketDisconnect(new ChatComponentTranslation("microblock.missing", missing.mkString(", ")))) ) {
} val missing = MicroMaterialRegistry.readIDMap(packet)
if (!missing.isEmpty)
netHandler.handleDisconnect(
new S40PacketDisconnect(
new ChatComponentTranslation(
"microblock.missing",
missing.mkString(", ")
)
)
)
}
} }
object MicroblockSPH extends MicroblockPH with IServerPacketHandler with IHandshakeHandler object MicroblockSPH
{ extends MicroblockPH
def handlePacket(packet: PacketCustom, sender: EntityPlayerMP, netHandler:INetHandlerPlayServer) {} with IServerPacketHandler
with IHandshakeHandler {
def handlePacket(
packet: PacketCustom,
sender: EntityPlayerMP,
netHandler: INetHandlerPlayServer
) {}
def handshakeRecieved(netHandler: NetHandlerPlayServer) { def handshakeRecieved(netHandler: NetHandlerPlayServer) {
val packet = new PacketCustom(registryChannel, 1) val packet = new PacketCustom(registryChannel, 1)
MicroMaterialRegistry.writeIDMap(packet) MicroMaterialRegistry.writeIDMap(packet)
netHandler.sendPacket(packet.toPacket) netHandler.sendPacket(packet.toPacket)
} }
} }
@@ -9,99 +9,134 @@ import cpw.mods.fml.relauncher.Side
import net.minecraft.item.crafting.CraftingManager import net.minecraft.item.crafting.CraftingManager
import net.minecraft.item.Item import net.minecraft.item.Item
import net.minecraft.item.crafting.IRecipe import net.minecraft.item.crafting.IRecipe
import java.util.{List => JList} import java.util.{List => JList}
import codechicken.lib.config.ConfigFile import codechicken.lib.config.ConfigFile
import net.minecraftforge.oredict.OreDictionary import net.minecraftforge.oredict.OreDictionary
import net.minecraft.item.ItemStack import net.minecraft.item.ItemStack
import net.minecraftforge.oredict.ShapedOreRecipe import net.minecraftforge.oredict.ShapedOreRecipe
import codechicken.lib.packet.PacketCustom import codechicken.lib.packet.PacketCustom
import codechicken.microblock.compat.PosteaCompat
import cpw.mods.fml.common.Loader
import cpw.mods.fml.common.registry.GameRegistry import cpw.mods.fml.common.registry.GameRegistry
import net.minecraft.client.renderer.RenderBlocks import net.minecraft.client.renderer.RenderBlocks
import net.minecraft.init.{Blocks, Items} import net.minecraft.init.{Blocks, Items}
import org.apache.logging.log4j.Logger import org.apache.logging.log4j.Logger
import scala.collection.mutable import scala.collection.mutable
class MicroblockProxy_serverImpl class MicroblockProxy_serverImpl {
{ var logger: Logger = _
var logger: Logger = _
var itemMicro: ItemMicroPart = _ var itemMicro: ItemMicroPart = _
var sawStone: Item = _ var sawStone: Item = _
var sawIron: Item = _ var sawIron: Item = _
var sawDiamond: Item = _ var sawDiamond: Item = _
var stoneRod: Item = _ var stoneRod: Item = _
var useSawIcons: Boolean = _ var useSawIcons: Boolean = _
def preInit(logger: Logger) { def preInit(logger: Logger) {
this.logger = logger this.logger = logger
itemMicro = new ItemMicroPart itemMicro = new ItemMicroPart
GameRegistry.registerItem(itemMicro, "microblock") GameRegistry.registerItem(itemMicro, "microblock")
sawStone = createSaw(config, "sawStone", 1) sawStone = createSaw(config, "sawStone", 1)
sawIron = createSaw(config, "sawIron", 2) sawIron = createSaw(config, "sawIron", 2)
sawDiamond = createSaw(config, "sawDiamond", 3) sawDiamond = createSaw(config, "sawDiamond", 3)
stoneRod = new Item().setUnlocalizedName("microblock:stoneRod").setTextureName("microblock:stoneRod") stoneRod = new Item()
GameRegistry.registerItem(stoneRod, "stoneRod") .setUnlocalizedName("microblock:stoneRod")
.setTextureName("microblock:stoneRod")
GameRegistry.registerItem(stoneRod, "stoneRod")
OreDictionary.registerOre("rodStone", stoneRod) OreDictionary.registerOre("rodStone", stoneRod)
MinecraftForge.EVENT_BUS.register(MicroblockEventHandler) MinecraftForge.EVENT_BUS.register(MicroblockEventHandler)
useSawIcons = config.getTag("useSawIcons").setComment("Set to true to use mc style icons for the saw instead of the 3D model").getBooleanValue(false) useSawIcons = config
.getTag("useSawIcons")
.setComment(
"Set to true to use mc style icons for the saw instead of the 3D model"
)
.getBooleanValue(false)
}
protected var saws = mutable.MutableList[Item]()
def createSaw(config: ConfigFile, name: String, strength: Int) = {
val saw = new ItemSaw(config.getTag(name).useBraces(), strength)
.setUnlocalizedName("microblock:" + name)
.setTextureName("microblock:" + name)
GameRegistry.registerItem(saw, name)
saws += saw
saw
}
def addSawRecipe(saw: Item, blade: Item) {
CraftingManager.getInstance.getRecipeList
.asInstanceOf[JList[IRecipe]]
.add(
new ShapedOreRecipe(
new ItemStack(saw),
"srr",
"sbr",
's': Character,
"stickWood",
'r': Character,
"rodStone",
'b': Character,
blade
)
)
}
def init() {
CraftingManager.getInstance.getRecipeList
.asInstanceOf[JList[IRecipe]]
.add(MicroRecipe)
if (!Loader.isModLoaded("dreamcraft")) {
CraftingManager.getInstance.addRecipe(
new ItemStack(stoneRod, 4),
"s",
"s",
's': Character,
Blocks.stone
)
addSawRecipe(sawStone, Items.flint)
addSawRecipe(sawIron, Items.iron_ingot)
addSawRecipe(sawDiamond, Items.diamond)
} }
}
protected var saws = mutable.MutableList[Item]() def postInit() {
def createSaw(config: ConfigFile, name: String, strength: Int) = { MicroMaterialRegistry.calcMaxCuttingStrength()
val saw = new ItemSaw(config.getTag(name).useBraces(), strength) PacketCustom.assignHandshakeHandler(
.setUnlocalizedName("microblock:" + name).setTextureName("microblock:" + name) MicroblockSPH.registryChannel,
GameRegistry.registerItem(saw, name) MicroblockSPH
saws+=saw )
saw if (Loader.isModLoaded("postea")) {
} PosteaCompat.registerTransformers()
def addSawRecipe(saw: Item, blade: Item) {
CraftingManager.getInstance.getRecipeList.asInstanceOf[JList[IRecipe]].add(
new ShapedOreRecipe(new ItemStack(saw),
"srr",
"sbr",
's': Character, "stickWood",
'r': Character, "rodStone",
'b': Character, blade))
}
def init() {
CraftingManager.getInstance.getRecipeList.asInstanceOf[JList[IRecipe]].add(MicroRecipe)
CraftingManager.getInstance.addRecipe(new ItemStack(stoneRod, 4), "s", "s", 's': Character, Blocks.stone)
addSawRecipe(sawStone, Items.flint)
addSawRecipe(sawIron, Items.iron_ingot)
addSawRecipe(sawDiamond, Items.diamond)
}
def postInit() {
MicroMaterialRegistry.calcMaxCuttingStrength()
PacketCustom.assignHandshakeHandler(MicroblockSPH.registryChannel, MicroblockSPH)
} }
}
} }
class MicroblockProxy_clientImpl extends MicroblockProxy_serverImpl class MicroblockProxy_clientImpl extends MicroblockProxy_serverImpl {
{ @SideOnly(Side.CLIENT)
@SideOnly(Side.CLIENT) lazy val renderBlocks = new RenderBlocks
lazy val renderBlocks = new RenderBlocks
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
override def postInit() { override def postInit() {
super.postInit() super.postInit()
MicroMaterialRegistry.loadIcons() MicroMaterialRegistry.loadIcons()
MinecraftForgeClient.registerItemRenderer(itemMicro, ItemMicroPartRenderer) MinecraftForgeClient.registerItemRenderer(itemMicro, ItemMicroPartRenderer)
PacketCustom.assignHandler(MicroblockCPH.registryChannel, MicroblockCPH) PacketCustom.assignHandler(MicroblockCPH.registryChannel, MicroblockCPH)
}
@SideOnly(Side.CLIENT) if (Loader.isModLoaded("angelica"))
override def init() { MicroblockMod.angelicaCompat = new AngelicaCompat
super.init() }
saws.foreach(MinecraftForgeClient.registerItemRenderer(_, ItemSawRenderer))
} @SideOnly(Side.CLIENT)
override def init() {
super.init()
saws.foreach(MinecraftForgeClient.registerItemRenderer(_, ItemSawRenderer))
}
} }
object MicroblockProxy extends MicroblockProxy_clientImpl object MicroblockProxy extends MicroblockProxy_clientImpl {}
{
}
@@ -2,7 +2,6 @@ package codechicken
import codechicken.microblock.handler.MicroblockProxy import codechicken.microblock.handler.MicroblockProxy
package object microblock package object microblock {
{ def logger = MicroblockProxy.logger
def logger = MicroblockProxy.logger
} }
@@ -3,7 +3,7 @@ package codechicken.multipart
import java.util.List import java.util.List
import java.lang.Iterable import java.lang.Iterable
import net.minecraft.block.Block import net.minecraft.block.Block
import net.minecraft.block.material.Material import net.minecraft.block.material.{MapColor, Material}
import net.minecraft.entity.Entity import net.minecraft.entity.Entity
import net.minecraft.util.AxisAlignedBB import net.minecraft.util.AxisAlignedBB
import net.minecraft.world.World import net.minecraft.world.World
@@ -12,6 +12,7 @@ import net.minecraft.util.Vec3
import net.minecraft.util.MovingObjectPosition import net.minecraft.util.MovingObjectPosition
import codechicken.lib.raytracer.RayTracer import codechicken.lib.raytracer.RayTracer
import net.minecraft.entity.player.EntityPlayer import net.minecraft.entity.player.EntityPlayer
import java.util.Random import java.util.Random
import java.util.ArrayList import java.util.ArrayList
import net.minecraft.item.ItemStack import net.minecraft.item.ItemStack
@@ -23,279 +24,426 @@ import net.minecraft.world.IBlockAccess
import codechicken.lib.raytracer.ExtendedMOP import codechicken.lib.raytracer.ExtendedMOP
import scala.collection.JavaConversions._ import scala.collection.JavaConversions._
object BlockMultipart object BlockMultipart {
{ def getTile(world: IBlockAccess, x: Int, y: Int, z: Int) =
def getTile(world:IBlockAccess, x:Int, y:Int, z:Int) = world.getTileEntity(x, y, z) match { world.getTileEntity(x, y, z) match {
case t:TileMultipart if !t.partList.isEmpty => t case t: TileMultipart if !t.partList.isEmpty => t
case _ => null case _ => null
} }
def getClientTile(world:IBlockAccess, x:Int, y:Int, z:Int) = world.getTileEntity(x, y, z) match { def getClientTile(world: IBlockAccess, x: Int, y: Int, z: Int) =
case t:TileMultipartClient if !t.partList.isEmpty => t world.getTileEntity(x, y, z) match {
case _ => null case t: TileMultipartClient if !t.partList.isEmpty => t
case _ => null
} }
def reduceMOP(hit:MovingObjectPosition):(Int, ExtendedMOP) = { def reduceMOP(hit: MovingObjectPosition): (Int, ExtendedMOP) = {
val ehit = hit.asInstanceOf[ExtendedMOP] val ehit = hit.asInstanceOf[ExtendedMOP]
val data:(Int, _) = ExtendedMOP.getData(hit) val data: (Int, _) = ExtendedMOP.getData(hit)
return (data._1, new ExtendedMOP(ehit, data._2, ehit.dist)) return (data._1, new ExtendedMOP(ehit, data._2, ehit.dist))
} }
def drawHighlight(world:World, player:EntityPlayer, hit:MovingObjectPosition, frame:Float):Boolean = def drawHighlight(
{ world: World,
val tile = getTile(world, hit.blockX, hit.blockY, hit.blockZ) player: EntityPlayer,
if(tile == null) hit: MovingObjectPosition,
return false frame: Float
): Boolean = {
val tile = getTile(world, hit.blockX, hit.blockY, hit.blockZ)
if (tile == null)
return false
val (index, mop) = reduceMOP(hit) val (index, mop) = reduceMOP(hit)
if(tile.partList(index).drawHighlight(mop, player, frame)) if (tile.partList(index).drawHighlight(mop, player, frame))
return true return true
tile.partList(index).collisionRayTrace(RayTracer.getStartVec(player), RayTracer.getEndVec(player)) tile
return false .partList(index)
} .collisionRayTrace(
RayTracer.getStartVec(player),
RayTracer.getEndVec(player)
)
return false
}
} }
/** /** Block class for all multiparts, should be internal use only.
* Block class for all multiparts, should be internal use only. */
*/ class BlockMultipart extends Block(new Material(MapColor.stoneColor)) {
class BlockMultipart extends Block(Material.rock) import BlockMultipart._
{
import BlockMultipart._
override def hasTileEntity(meta:Int = 0) = true override def hasTileEntity(meta: Int = 0) = true
override def isBlockSolid(world:IBlockAccess, x:Int, y:Int, z:Int, side:Int):Boolean = override def isBlockSolid(
getTile(world, x, y, z) match { world: IBlockAccess,
case null => false x: Int,
case tile => tile.isSolid(side) y: Int,
} z: Int,
side: Int
override def isSideSolid(world:IBlockAccess, x:Int, y:Int, z:Int, side:ForgeDirection):Boolean = ): Boolean =
isBlockSolid(world, x, y, z, side.ordinal()) getTile(world, x, y, z) match {
case null => false
override def canPlaceTorchOnTop(world:World, x:Int, y:Int, z:Int) = case tile => tile.isSolid(side)
getTile(world, x, y, z) match {
case null => false
case tile => tile.canPlaceTorchOnTop
}
override def onNeighborBlockChange(world:World, x:Int, y:Int, z:Int, block:Block) {
val tile = getTile(world, x, y, z)
if(tile != null)
tile.onNeighborBlockChange()
} }
override def collisionRayTrace(world:World, x:Int, y:Int, z:Int, start:Vec3, end:Vec3):ExtendedMOP = override def isSideSolid(
getTile(world, x, y, z) match { world: IBlockAccess,
case null => null x: Int,
case tile => tile.collisionRayTrace(start, end) y: Int,
} z: Int,
side: ForgeDirection
): Boolean =
isBlockSolid(world, x, y, z, side.ordinal())
def rayTraceAll(world:World, x:Int, y:Int, z:Int, start:Vec3, end:Vec3):Iterable[ExtendedMOP] = override def canPlaceTorchOnTop(world: World, x: Int, y: Int, z: Int) =
getTile(world, x, y, z) match { getTile(world, x, y, z) match {
case null => Seq() case null => false
case tile => tile.rayTraceAll(start, end) case tile => tile.canPlaceTorchOnTop
}
override def removedByPlayer(world:World, player:EntityPlayer, x:Int, y:Int, z:Int):Boolean = {
val hit = RayTracer.retraceBlock(world, player, x, y, z)
val tile = getTile(world, x, y, z)
if(hit == null || tile == null)
{
dropAndDestroy(world, x, y, z)
return true
}
val (index, mop) = reduceMOP(hit)
if(world.isRemote)
{
tile.partList(index).addDestroyEffects(mop, Minecraft.getMinecraft.effectRenderer)
return true
}
tile.harvestPart(index, mop, player)
return world.getTileEntity(x, y, z) == null
} }
def dropAndDestroy(world:World, x:Int, y:Int, z:Int) { override def onNeighborBlockChange(
val tile = getTile(world, x, y, z) world: World,
if(tile != null && !world.isRemote) x: Int,
tile.dropItems(getDrops(world, x, y, z, 0, 0)) y: Int,
z: Int,
block: Block
) {
val tile = getTile(world, x, y, z)
if (tile != null)
tile.onNeighborBlockChange()
}
world.setBlockToAir(x, y, z) override def collisionRayTrace(
world: World,
x: Int,
y: Int,
z: Int,
start: Vec3,
end: Vec3
): ExtendedMOP =
getTile(world, x, y, z) match {
case null => null
case tile => tile.collisionRayTrace(start, end)
} }
override def quantityDropped(meta:Int, fortune:Int, random:Random) = 0 def rayTraceAll(
world: World,
override def getDrops(world:World, x:Int, y:Int, z:Int, meta:Int, fortune:Int):ArrayList[ItemStack] = { x: Int,
val ai = new ArrayList[ItemStack]() y: Int,
if(world.isRemote) z: Int,
return ai start: Vec3,
end: Vec3
val tile = getTile(world, x, y, z) ): Iterable[ExtendedMOP] =
if(tile != null) getTile(world, x, y, z) match {
tile.partList.foreach(part => part.getDrops.foreach(item => ai.add(item))) case null => Seq()
case tile => tile.rayTraceAll(start, end)
return ai
} }
override def addCollisionBoxesToList(world:World, x:Int, y:Int, z:Int, ebb:AxisAlignedBB, list$:List[_], entity:Entity) { override def removedByPlayer(
val list = list$.asInstanceOf[List[AxisAlignedBB]] world: World,
val tile = getTile(world, x, y, z) player: EntityPlayer,
if(tile != null) x: Int,
tile.partList.foreach(part => y: Int,
part.getCollisionBoxes.foreach{c => z: Int
val aabb = c.toAABB.offset(x, y, z) ): Boolean = {
if(aabb.intersectsWith(ebb)) val hit = RayTracer.retraceBlock(world, player, x, y, z)
list.add(aabb) val tile = getTile(world, x, y, z)
})
if (hit == null || tile == null) {
dropAndDestroy(world, x, y, z)
return true
} }
override def addHitEffects(world:World, hit:MovingObjectPosition, effectRenderer:EffectRenderer):Boolean = { val (index, mop) = reduceMOP(hit)
val tile = getClientTile(world, hit.blockX, hit.blockY, hit.blockZ) if (world.isRemote) {
if(tile != null) { tile
val (index, mop) = reduceMOP(hit) .partList(index)
if(index < tile.partList.size) .addDestroyEffects(mop, Minecraft.getMinecraft.effectRenderer)
tile.partList(index).addHitEffects(mop, effectRenderer) return true
}
tile.harvestPart(index, mop, player)
return world.getTileEntity(x, y, z) == null
}
def dropAndDestroy(world: World, x: Int, y: Int, z: Int) {
val tile = getTile(world, x, y, z)
if (tile != null && !world.isRemote)
tile.dropItems(getDrops(world, x, y, z, 0, 0))
world.setBlockToAir(x, y, z)
}
override def quantityDropped(meta: Int, fortune: Int, random: Random) = 0
override def getDrops(
world: World,
x: Int,
y: Int,
z: Int,
meta: Int,
fortune: Int
): ArrayList[ItemStack] = {
val ai = new ArrayList[ItemStack]()
if (world.isRemote)
return ai
val tile = getTile(world, x, y, z)
if (tile != null)
tile.partList.foreach(part => part.getDrops.foreach(item => ai.add(item)))
return ai
}
override def addCollisionBoxesToList(
world: World,
x: Int,
y: Int,
z: Int,
ebb: AxisAlignedBB,
list$ : List[_],
entity: Entity
) {
val list = list$.asInstanceOf[List[AxisAlignedBB]]
val tile = getTile(world, x, y, z)
if (tile != null)
tile.partList.foreach(part =>
part.getCollisionBoxes.foreach { c =>
val aabb = c.toAABB.offset(x, y, z)
if (aabb.intersectsWith(ebb))
list.add(aabb)
} }
)
}
return true override def addHitEffects(
world: World,
hit: MovingObjectPosition,
effectRenderer: EffectRenderer
): Boolean = {
val tile = getClientTile(world, hit.blockX, hit.blockY, hit.blockZ)
if (tile != null) {
val (index, mop) = reduceMOP(hit)
if (index < tile.partList.size)
tile.partList(index).addHitEffects(mop, effectRenderer)
} }
override def addDestroyEffects(world:World, x:Int, y:Int, z:Int, s:Int, effectRenderer:EffectRenderer) = true return true
}
override def renderAsNormalBlock() = false override def addDestroyEffects(
world: World,
x: Int,
y: Int,
z: Int,
s: Int,
effectRenderer: EffectRenderer
) = true
override def isOpaqueCube = false override def renderAsNormalBlock() = false
override def getRenderType = TileMultipart.renderID override def isOpaqueCube = false
override def isAir(world:IBlockAccess, x:Int, y:Int, z:Int):Boolean = override def getRenderType = TileMultipart.renderID
getTile(world, x, y, z) match {
case null => true
case tile => tile.partList.isEmpty
}
override def isReplaceable(world:IBlockAccess, x:Int, y:Int, z:Int) = isAir(world, x, y, z) override def isAir(world: IBlockAccess, x: Int, y: Int, z: Int): Boolean =
getTile(world, x, y, z) match {
override def getRenderBlockPass = 1 case null => true
case tile => tile.partList.isEmpty
override def canRenderInPass(pass:Int):Boolean = {
MultipartRenderer.pass = pass
return true
} }
override def getPickBlock(hit:MovingObjectPosition, world:World, x:Int, y:Int, z:Int):ItemStack = { override def isReplaceable(world: IBlockAccess, x: Int, y: Int, z: Int) =
val tile = getTile(world, x, y, z) isAir(world, x, y, z)
if(tile != null)
{ override def getRenderBlockPass = 1
val (index, mop) = reduceMOP(hit)
return tile.partList(index).pickItem(mop) override def canRenderInPass(pass: Int): Boolean = true
}
override def getPickBlock(
hit: MovingObjectPosition,
world: World,
x: Int,
y: Int,
z: Int
): ItemStack = {
val tile = getTile(world, x, y, z)
if (tile != null) {
if (!hit.isInstanceOf[ExtendedMOP]) {
return null return null
}
val (index, mop) = reduceMOP(hit)
return tile.partList(index).pickItem(mop)
}
return null
}
override def getPlayerRelativeBlockHardness(
player: EntityPlayer,
world: World,
x: Int,
y: Int,
z: Int
): Float = {
val hit = RayTracer.retraceBlock(world, player, x, y, z)
val tile = getTile(world, x, y, z)
if (hit != null && tile != null) {
val (index, mop) = reduceMOP(hit)
return tile.partList(index).getStrength(mop, player) / 30f
} }
override def getPlayerRelativeBlockHardness(player:EntityPlayer, world:World, x:Int, y:Int, z:Int):Float = { return 1 / 100f
val hit = RayTracer.retraceBlock(world, player, x, y, z) }
val tile = getTile(world, x, y, z)
if(hit != null && tile != null) {
val (index, mop) = reduceMOP(hit)
return tile.partList(index).getStrength(mop, player)/30F
}
return 1/100F /** Kludge to set PROTECTED blockIcon to a blank icon
*/
override def registerBlockIcons(register: IIconRegister) {
val icon = TextureUtils.getBlankIcon(16, register)
setBlockTextureName(icon.getIconName)
super.registerBlockIcons(register)
}
override def getLightValue(world: IBlockAccess, x: Int, y: Int, z: Int): Int =
getTile(world, x, y, z) match {
case null => 0
case tile => tile.getLightValue
} }
/** override def randomDisplayTick(
* Kludge to set PROTECTED blockIcon to a blank icon world: World,
*/ x: Int,
override def registerBlockIcons(register:IIconRegister) { y: Int,
val icon = TextureUtils.getBlankIcon(16, register) z: Int,
setBlockTextureName(icon.getIconName) random: Random
super.registerBlockIcons(register) ) {
val tile = getClientTile(world, x, y, z)
if (tile != null)
tile.randomDisplayTick(random)
}
override def onBlockActivated(
world: World,
x: Int,
y: Int,
z: Int,
player: EntityPlayer,
side: Int,
hitX: Float,
hitY: Float,
hitZ: Float
): Boolean = {
val hit = RayTracer.retraceBlock(world, player, x, y, z)
if (hit == null)
return false
val tile = getTile(world, x, y, z)
if (tile == null)
return false
val (index, mop) = reduceMOP(hit)
return tile.partList(index).activate(player, mop, player.getHeldItem)
}
override def onBlockClicked(
world: World,
x: Int,
y: Int,
z: Int,
player: EntityPlayer
) {
val hit = RayTracer.retraceBlock(world, player, x, y, z)
if (hit == null)
return
val tile = getTile(world, x, y, z)
if (tile == null)
return
val (index, mop) = reduceMOP(hit)
tile.partList(index).click(player, mop, player.getHeldItem)
}
override def isProvidingStrongPower(
world: IBlockAccess,
x: Int,
y: Int,
z: Int,
side: Int
): Int =
getTile(world, x, y, z) match {
case null => 0
case tile => tile.strongPowerLevel(side ^ 1)
} }
override def getLightValue(world:IBlockAccess, x:Int, y:Int, z:Int):Int = override def isProvidingWeakPower(
getTile(world, x, y, z) match { world: IBlockAccess,
case null => 0 x: Int,
case tile => tile.getLightValue y: Int,
} z: Int,
side: Int
override def randomDisplayTick(world:World, x:Int, y:Int, z:Int, random:Random) { ): Int =
val tile = getClientTile(world, x, y, z) getTile(world, x, y, z) match {
if(tile != null) case null => 0
tile.randomDisplayTick(random) case tile => tile.weakPowerLevel(side ^ 1)
} }
override def onBlockActivated(world:World, x:Int, y:Int, z:Int, player:EntityPlayer, side:Int, hitX:Float, hitY:Float, hitZ:Float):Boolean = { override def canConnectRedstone(
val hit = RayTracer.retraceBlock(world, player, x, y, z) world: IBlockAccess,
if(hit == null) x: Int,
return false y: Int,
z: Int,
val tile = getTile(world, x, y, z) side: Int
if(tile == null) ): Boolean =
return false getTile(world, x, y, z) match {
case null => false
val (index, mop) = reduceMOP(hit) case tile => tile.canConnectRedstone(side)
return tile.partList(index).activate(player, mop, player.getHeldItem)
} }
override def onBlockClicked(world:World, x:Int, y:Int, z:Int, player:EntityPlayer) { override def onEntityCollidedWithBlock(
val hit = RayTracer.retraceBlock(world, player, x, y, z) world: World,
if(hit == null) x: Int,
return y: Int,
z: Int,
entity: Entity
) {
val tile = getTile(world, x, y, z)
if (tile != null)
tile.onEntityCollision(entity)
}
val tile = getTile(world, x, y, z) override def onNeighborChange(
if(tile == null) world: IBlockAccess,
return x: Int,
y: Int,
z: Int,
tileX: Int,
tileY: Int,
tileZ: Int
) {
val tile = getTile(world, x, y, z)
if (tile != null)
tile.onNeighborTileChange(tileX, tileY, tileZ)
}
val (index, mop) = reduceMOP(hit) override def getExplosionResistance(
tile.partList(index).click(player, mop, player.getHeldItem) entity: Entity,
world: World,
x: Int,
y: Int,
z: Int,
explosionX: Double,
explosionY: Double,
explosionZ: Double
): Float =
getTile(world, x, y, z) match {
case null => 0
case tile => tile.getExplosionResistance(entity)
} }
override def isProvidingStrongPower(world:IBlockAccess, x:Int, y:Int, z:Int, side:Int):Int = override def getWeakChanges(world: IBlockAccess, x: Int, y: Int, z: Int) =
getTile(world, x, y, z) match { getTile(world, x, y, z) match {
case null => 0 case null => false
case tile => tile.strongPowerLevel(side^1) case tile => tile.getWeakChanges
}
override def isProvidingWeakPower(world:IBlockAccess, x:Int, y:Int, z:Int, side:Int):Int =
getTile(world, x, y, z) match {
case null => 0
case tile => tile.weakPowerLevel(side^1)
}
override def canConnectRedstone(world:IBlockAccess, x:Int, y:Int, z:Int, side:Int):Boolean =
getTile(world, x, y, z) match {
case null => false
case tile => tile.canConnectRedstone(side)
}
override def onEntityCollidedWithBlock(world:World, x:Int, y:Int, z:Int, entity:Entity) {
val tile = getTile(world, x, y, z)
if(tile != null)
tile.onEntityCollision(entity)
} }
override def onNeighborChange(world:IBlockAccess, x:Int, y:Int, z:Int, tileX:Int, tileY:Int, tileZ:Int) { override def canProvidePower = true
val tile = getTile(world, x, y, z)
if(tile != null)
tile.onNeighborTileChange(tileX, tileY, tileZ)
}
override def getExplosionResistance(entity:Entity, world:World, x:Int, y:Int, z:Int, explosionX:Double, explosionY:Double, explosionZ:Double):Float =
getTile(world, x, y, z) match {
case null => 0
case tile => tile.getExplosionResistance(entity)
}
override def getWeakChanges(world:IBlockAccess, x:Int, y:Int, z:Int) =
getTile(world, x, y, z) match {
case null => false
case tile => tile.getWeakChanges
}
override def canProvidePower = true
} }
@@ -11,47 +11,53 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent
import cpw.mods.fml.relauncher.{Side, SideOnly} import cpw.mods.fml.relauncher.{Side, SideOnly}
import cpw.mods.fml.common.gameevent.TickEvent.ClientTickEvent import cpw.mods.fml.common.gameevent.TickEvent.ClientTickEvent
/** /** A class that maintains a map server<->client of which players are holding
* A class that maintains a map server<->client of which players are holding the control (or placement modifier key) much like sneaking. * the control (or placement modifier key) much like sneaking.
*/ */
object ControlKeyModifer object ControlKeyModifer {
{ implicit def playerControlValue(p: EntityPlayer) = new ControlKeyValue(p)
implicit def playerControlValue(p:EntityPlayer) = new ControlKeyValue(p)
class ControlKeyValue(p:EntityPlayer) class ControlKeyValue(p: EntityPlayer) {
{ def isControlDown = {
def isControlDown = map(p) if (p.worldObj.isRemote) {
isClientPressing
} else {
map(p)
}
} }
}
val map = HashMap[EntityPlayer, Boolean]().withDefaultValue(false) val map = HashMap[EntityPlayer, Boolean]().withDefaultValue(false)
var isClientPressing = false;
/** /** Implicit static for Java users.
* Implicit static for Java users. */
*/ def isControlDown(p: EntityPlayer) = p.isControlDown
def isControlDown(p:EntityPlayer) = p.isControlDown
} }
/** /** Key Handler implementation
* Key Handler implementation */
*/ object ControlKeyHandler
object ControlKeyHandler extends KeyBinding("key.control", Keyboard.KEY_LCONTROL, "key.categories.gameplay") extends KeyBinding(
{ "key.control",
import ControlKeyModifer._ Keyboard.KEY_NONE,
var wasPressed = false "Forge Multipart"
) {
import ControlKeyModifer._
var wasPressed = false
@SubscribeEvent @SubscribeEvent
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
def tick(event:ClientTickEvent) { def tick(event: ClientTickEvent) {
val pressed = getIsKeyPressed val pressed = getIsKeyPressed
if(pressed != wasPressed) { if (pressed != wasPressed) {
wasPressed = pressed wasPressed = pressed
if(Minecraft.getMinecraft.getNetHandler != null) if (Minecraft.getMinecraft.getNetHandler != null) {
{ isClientPressing = pressed
map.put(Minecraft.getMinecraft.thePlayer, pressed) val packet = new PacketCustom(MultipartCPH.channel, 1)
val packet = new PacketCustom(MultipartCPH.channel, 1) packet.writeBoolean(pressed)
packet.writeBoolean(pressed) packet.sendToServer()
packet.sendToServer() }
}
}
} }
}
} }
@@ -3,31 +3,24 @@ package codechicken.multipart
import codechicken.lib.data.MCDataOutput import codechicken.lib.data.MCDataOutput
import codechicken.lib.data.MCDataInput import codechicken.lib.data.MCDataInput
/** /** Class for reading and writing ids, widening the carrier data type as
* Class for reading and writing ids, widening the carrier data type as necessary * necessary
*/ */
class IDWriter class IDWriter {
{ var write: (MCDataOutput, Int) => Unit = _
var write:(MCDataOutput, Int)=>Unit = _ var read: (MCDataInput) => Int = _
var read:(MCDataInput)=>Int = _
def setMax(i:Int) def setMax(i: Int) {
{ val l = i.toLong & 0xffffffff
val l = i.toLong & 0xFFFFFFFF if (l > 0xffff) {
if(l > 0xFFFF) write = (data, i) => data.writeInt(i)
{ read = (data) => data.readInt()
write = (data, i) => data.writeInt(i) } else if (l > 0xff) {
read = (data) => data.readInt() write = (data, i) => data.writeShort(i)
} read = (data) => data.readUShort()
else if(l > 0xFF) } else {
{ write = (data, i) => data.writeByte(i)
write = (data, i) => data.writeShort(i) read = (data) => data.readUByte()
read = (data) => data.readUShort()
}
else
{
write = (data, i) => data.writeByte(i)
read = (data) => data.readUByte()
}
} }
}
} }
@@ -1,15 +1,16 @@
package codechicken.multipart package codechicken.multipart
/** /** Mixin interface for parts that want to be notified of neighbor tile change
* Mixin interface for parts that want to be notified of neighbor tile change events (comparators or inventory maintainers) * events (comparators or inventory maintainers)
*/ */
trait INeighborTileChange { trait INeighborTileChange {
/**
* Returns whether this part needs calls for tile changes through one solid block /** Returns whether this part needs calls for tile changes through one solid
*/ * block
def weakTileChanges():Boolean */
/** def weakTileChanges(): Boolean
* Callback for neighbor tile changes, from same function in Block
*/ /** Callback for neighbor tile changes, from same function in Block
def onNeighborTileChanged(side:Int, weak:Boolean) */
def onNeighborTileChanged(side: Int, weak: Boolean)
} }
@@ -2,15 +2,13 @@ package codechicken.multipart
import java.util.Random import java.util.Random
/** /** Interface for parts that need random display ticks (torches)
* Interface for parts that need random display ticks (torches) *
* * Marker interface for TRandomDisplayTickTile
* Marker interface for TRandomDisplayTickTile */
*/ trait IRandomDisplayTick {
trait IRandomDisplayTick
{ /** Called on a random display tick.
/** */
* Called on a random display tick. def randomDisplayTick(random: Random)
*/
def randomDisplayTick(random:Random)
} }
@@ -7,237 +7,304 @@ import net.minecraft.util.Direction
import codechicken.lib.vec.Rotation._ import codechicken.lib.vec.Rotation._
import net.minecraft.init.Blocks import net.minecraft.init.Blocks
/** /** Interface for parts with redstone interaction
* Interface for parts with redstone interaction *
* * Marker interface for TRedstoneTile. This means that if a part is an instance
* Marker interface for TRedstoneTile. This means that if a part is an instance of IRedstonePart, the container tile may be cast to TRedstoneTile * of IRedstonePart, the container tile may be cast to TRedstoneTile
*/ */
trait IRedstonePart trait IRedstonePart {
{
/** /** Returns the strong (indirect, through blocks) signal being emitted by this
* Returns the strong (indirect, through blocks) signal being emitted by this part to the specified side * part to the specified side
*/ */
def strongPowerLevel(side:Int):Int def strongPowerLevel(side: Int): Int
/**
* Returns the weak (direct) signal being emitted by this part to the specified side /** Returns the weak (direct) signal being emitted by this part to the
*/ * specified side
def weakPowerLevel(side:Int):Int */
/** def weakPowerLevel(side: Int): Int
* Returns true if this part can connect to redstone on the specified side. Blocking parts like covers will be handled by RedstoneInteractions
*/ /** Returns true if this part can connect to redstone on the specified side.
def canConnectRedstone(side:Int):Boolean * Blocking parts like covers will be handled by RedstoneInteractions
*/
def canConnectRedstone(side: Int): Boolean
} }
/** /** For parts like wires that adhere to a specific face, reduces redstone
* For parts like wires that adhere to a specific face, reduces redstone connections to the specific edge between two faces. * connections to the specific edge between two faces. Should be implemented on
* Should be implemented on parts implementing TFacePart * parts implementing TFacePart
*/ */
trait IFaceRedstonePart extends IRedstonePart trait IFaceRedstonePart extends IRedstonePart {
{
/** /** Return the face to which this redstone part is attached
* Return the face to which this redstone part is attached */
*/ def getFace: Int
def getFace:Int
} }
/** /** For parts that want to define their own connection masks (like center-center
* For parts that want to define their own connection masks (like center-center parts) * parts)
*/ */
trait IMaskedRedstonePart extends IRedstonePart trait IMaskedRedstonePart extends IRedstonePart {
{
/** /** Returns the redstone connection mask for this part on side. See
* Returns the redstone connection mask for this part on side. See IRedstoneConnector for mask definition * IRedstoneConnector for mask definition
*/ */
def getConnectionMask(side:Int):Int def getConnectionMask(side: Int): Int
} }
/** /** Interface for tile entities which split their redstone connections into a
* Interface for tile entities which split their redstone connections into a mask for each side (edges and center) * mask for each side (edges and center)
* *
* All connection masks are a 5 bit map. * All connection masks are a 5 bit map. The lowest 4 bits correspond to the
* The lowest 4 bits correspond to the connection toward the face specified Rotation.rotateSide(side&6, b) where b is the bit index from lowest to highest. * connection toward the face specified Rotation.rotateSide(side&6, b) where b
* Bit 5 corresponds to a connection opposite side. * is the bit index from lowest to highest. Bit 5 corresponds to a connection
*/ * opposite side.
trait IRedstoneConnector */
{ trait IRedstoneConnector {
/**
* Returns the redstone connection mask for this tile on side. /** Returns the redstone connection mask for this tile on side.
*/ */
def getConnectionMask(side:Int):Int def getConnectionMask(side: Int): Int
/**
* Returns the weak power level provided by this tile on side through mask /** Returns the weak power level provided by this tile on side through mask
*/ */
def weakPowerLevel(side:Int, mask:Int):Int def weakPowerLevel(side: Int, mask: Int): Int
} }
/** /** Internal interface for TileMultipart instances hosting IRedstonePart
* Internal interface for TileMultipart instances hosting IRedstonePart */
*/ trait IRedstoneTile extends IRedstoneConnector {
trait IRedstoneTile extends IRedstoneConnector
{ /** Returns a mask of spaces through which a wire could connect on side
/** */
* Returns a mask of spaces through which a wire could connect on side def openConnections(side: Int): Int
*/
def openConnections(side:Int):Int
} }
/** /** Block version of IRedstoneConnector Due to the inadequate
* Block version of IRedstoneConnector * Block.canConnectRedstone not handling the bottom side (nor the top
* Due to the inadequate Block.canConnectRedstone not handling the bottom side (nor the top particularly well) * particularly well)
*/ */
trait IRedstoneConnectorBlock trait IRedstoneConnectorBlock {
{ def getConnectionMask(
def getConnectionMask(world:IBlockAccess, x:Int, y:Int, z:Int, side:Int):Int world: IBlockAccess,
def weakPowerLevel(world:IBlockAccess, x:Int, y:Int, z:Int, side:Int, mask:Int):Int x: Int,
y: Int,
z: Int,
side: Int
): Int
def weakPowerLevel(
world: IBlockAccess,
x: Int,
y: Int,
z: Int,
side: Int,
mask: Int
): Int
} }
/** /** static helper class for calculating various things about redstone. Indirect
* static helper class for calculating various things about redstone. * power (also known as strong power) is not handled here, just use
* Indirect power (also known as strong power) is not handled here, just use world.getIndirectPowerTo * world.getIndirectPowerTo Masks are defined in IRedstoneConnector
* Masks are defined in IRedstoneConnector */
*/ object RedstoneInteractions {
object RedstoneInteractions import net.minecraft.util.Facing._
{
import net.minecraft.util.Facing._
val vanillaSideMap = Array(-2, -1, 0, 2, 3, 1) val vanillaSideMap = Array(-2, -1, 0, 2, 3, 1)
val sideVanillaMap = Array(1, 2, 5, 3, 4) val sideVanillaMap = Array(1, 2, 5, 3, 4)
/** /** Hardcoded vanilla overrides for Block.canConnectRedstone (see
* Hardcoded vanilla overrides for Block.canConnectRedstone (see @IRedstoneConnectorBlock) * \@IRedstoneConnectorBlock)
*/ */
val fullVanillaBlocks = Set( val fullVanillaBlocks = Set(
Blocks.redstone_torch, Blocks.redstone_torch,
Blocks.unlit_redstone_torch, Blocks.unlit_redstone_torch,
Blocks.lever, Blocks.lever,
Blocks.stone_button, Blocks.stone_button,
Blocks.wooden_button, Blocks.wooden_button,
Blocks.redstone_block) Blocks.redstone_block
)
/** /** Get the direct power to p on side
* Get the direct power to p on side */
*/ def getPowerTo(p: TMultiPart, side: Int): Int = {
def getPowerTo(p:TMultiPart, side:Int):Int = val tile = p.tile
{ return getPowerTo(
val tile = p.tile tile.getWorldObj,
return getPowerTo(tile.getWorldObj, tile.xCoord, tile.yCoord, tile.zCoord, side, tile.xCoord,
tile.asInstanceOf[IRedstoneTile].openConnections(side)&connectionMask(p, side)) tile.yCoord,
tile.zCoord,
side,
tile.asInstanceOf[IRedstoneTile].openConnections(side) & connectionMask(
p,
side
)
)
}
/** Get the direct power level to space (x, y, z) on side with mask
*/
def getPowerTo(
world: World,
x: Int,
y: Int,
z: Int,
side: Int,
mask: Int
): Int =
getPower(
world,
x + offsetsXForSide(side),
y + offsetsYForSide(side),
z + offsetsZForSide(side),
side ^ 1,
mask
)
/** Get the direct power level provided by space (x, y, z) on side with mask
*/
def getPower(
world: World,
x: Int,
y: Int,
z: Int,
side: Int,
mask: Int
): Int = {
val tile = world.getTileEntity(x, y, z)
if (tile.isInstanceOf[IRedstoneConnector])
return tile.asInstanceOf[IRedstoneConnector].weakPowerLevel(side, mask)
val block = world.getBlock(x, y, z)
if (block.isInstanceOf[IRedstoneConnectorBlock])
return block
.asInstanceOf[IRedstoneConnectorBlock]
.weakPowerLevel(world, x, y, z, side, mask)
val vmask = vanillaConnectionMask(block, world, x, y, z, side, true)
if ((vmask & mask) > 0) {
var m = world.getIndirectPowerLevelTo(x, y, z, side ^ 1)
if (m < 15 && block == Blocks.redstone_wire)
m =
Math.max(m, world.getBlockMetadata(x, y, z)) // painful vanilla kludge
return m
}
return 0
}
def vanillaToSide(vside: Int) = sideVanillaMap(vside + 1)
/** Get the connection mask of the block on side of (x, y, z).
* @param power,
* whether the connection mask is for signal transfer or visual connection.
* (some blocks accept power without visual connection)
*/
def otherConnectionMask(
world: IBlockAccess,
x: Int,
y: Int,
z: Int,
side: Int,
power: Boolean
): Int =
getConnectionMask(
world,
x + offsetsXForSide(side),
y + offsetsYForSide(side),
z + offsetsZForSide(side),
side ^ 1,
power
)
/** Get the connection mask of part on side
*/
def connectionMask(p: TMultiPart, side: Int): Int = {
if (
p.isInstanceOf[IRedstonePart] && p
.asInstanceOf[IRedstonePart]
.canConnectRedstone(side)
) {
if (p.isInstanceOf[IFaceRedstonePart]) {
val fside = p.asInstanceOf[IFaceRedstonePart].getFace
if ((side & 6) == (fside & 6))
return 0x10
return 1 << rotationTo(side & 6, fside)
} else if (p.isInstanceOf[IMaskedRedstonePart]) {
return p.asInstanceOf[IMaskedRedstonePart].getConnectionMask(side)
}
return 0x1f
}
return 0
}
/** @param power
* If true, don't test canConnectRedstone on blocks, just get a power
* transmission mask rather than a visual connection
*/
def getConnectionMask(
world: IBlockAccess,
x: Int,
y: Int,
z: Int,
side: Int,
power: Boolean
): Int = {
val tile = world.getTileEntity(x, y, z)
if (tile.isInstanceOf[IRedstoneConnector])
return tile.asInstanceOf[IRedstoneConnector].getConnectionMask(side)
val block = world.getBlock(x, y, z)
if (block.isInstanceOf[IRedstoneConnectorBlock])
return block
.asInstanceOf[IRedstoneConnectorBlock]
.getConnectionMask(world, x, y, z, side)
return vanillaConnectionMask(block, world, x, y, z, side, power)
}
/** Returns the connection mask for a vanilla block
*/
def vanillaConnectionMask(
block: Block,
world: IBlockAccess,
x: Int,
y: Int,
z: Int,
side: Int,
power: Boolean
): Int = {
if (fullVanillaBlocks(block))
return 0x1f
/** so that these can be conducted to from face parts on the other side of
* the block. Due to vanilla's in adequecy with redstone/logic on walls
*/
if (
block == Blocks.redstone_wire || block == Blocks.powered_comparator || block == Blocks.unpowered_comparator
) {
if (side != 0)
return if (power) 0x1f else 4
return 0
} }
/** val vside = vanillaSideMap(side)
* Get the direct power level to space (x, y, z) on side with mask if (
*/ block == Blocks.powered_repeater || block == Blocks.unpowered_repeater
def getPowerTo(world:World, x:Int, y:Int, z:Int, side:Int, mask:Int):Int = ) // stupid minecraft hardcodes
getPower(world, x+offsetsXForSide(side), y+offsetsYForSide(side), z+offsetsZForSide(side), side^1, mask) {
val meta = world.getBlockMetadata(x, y, z)
/** if (vside == (meta & 3) || vside == Direction.rotateOpposite(meta & 3))
* Get the direct power level provided by space (x, y, z) on side with mask return if (power) 0x1f else 4
*/
def getPower(world:World, x:Int, y:Int, z:Int, side:Int, mask:Int):Int =
{
val tile = world.getTileEntity(x, y, z)
if(tile.isInstanceOf[IRedstoneConnector])
return tile.asInstanceOf[IRedstoneConnector].weakPowerLevel(side, mask)
val block = world.getBlock(x, y, z)
if(block.isInstanceOf[IRedstoneConnectorBlock])
return block.asInstanceOf[IRedstoneConnectorBlock].weakPowerLevel(world, x, y, z, side, mask)
val vmask = vanillaConnectionMask(block, world, x, y, z, side, true)
if((vmask&mask) > 0)
{
var m = world.getIndirectPowerLevelTo(x, y, z, side^1)
if(m < 15 && block == Blocks.redstone_wire)
m = Math.max(m, world.getBlockMetadata(x, y, z))//painful vanilla kludge
return m
}
return 0
}
def vanillaToSide(vside:Int) = sideVanillaMap(vside+1)
/**
* Get the connection mask of the block on side of (x, y, z).
* @param power, whether the connection mask is for signal transfer or visual connection. (some blocks accept power without visual connection)
*/
def otherConnectionMask(world:IBlockAccess, x:Int, y:Int, z:Int, side:Int, power:Boolean):Int =
getConnectionMask(world, x+offsetsXForSide(side), y+offsetsYForSide(side), z+offsetsZForSide(side), side^1, power)
/**
* Get the connection mask of part on side
*/
def connectionMask(p:TMultiPart, side:Int):Int =
{
if(p.isInstanceOf[IRedstonePart] && p.asInstanceOf[IRedstonePart].canConnectRedstone(side))
{
if(p.isInstanceOf[IFaceRedstonePart])
{
val fside = p.asInstanceOf[IFaceRedstonePart].getFace
if((side&6) == (fside&6))
return 0x10
return 1<<rotationTo(side&6, fside)
}
else if(p.isInstanceOf[IMaskedRedstonePart])
{
return p.asInstanceOf[IMaskedRedstonePart].getConnectionMask(side)
}
return 0x1F
}
return 0
}
/**
* @param power If true, don't test canConnectRedstone on blocks, just get a power transmission mask rather than a visual connection
*/
def getConnectionMask(world:IBlockAccess, x:Int, y:Int, z:Int, side:Int, power:Boolean):Int =
{
val tile = world.getTileEntity(x, y, z)
if(tile.isInstanceOf[IRedstoneConnector])
return tile.asInstanceOf[IRedstoneConnector].getConnectionMask(side)
val block = world.getBlock(x, y, z)
if(block.isInstanceOf[IRedstoneConnectorBlock])
return block.asInstanceOf[IRedstoneConnectorBlock].getConnectionMask(world, x, y, z, side)
return vanillaConnectionMask(block, world, x, y, z, side, power)
}
/**
* Returns the connection mask for a vanilla block
*/
def vanillaConnectionMask(block:Block, world:IBlockAccess, x:Int, y:Int, z:Int, side:Int, power:Boolean):Int =
{
if(fullVanillaBlocks(block))
return 0x1F
if(side == 0)//vanilla doesn't handle side 0
return if(power) 0x1F else 0
/**
* so that these can be conducted to from face parts on the other side of the block.
* Due to vanilla's in adequecy with redstone/logic on walls
*/
if(block == Blocks.redstone_wire || block == Blocks.powered_comparator || block == Blocks.unpowered_comparator) {
if(side != 0)
return if(power) 0x1F else 4
return 0
}
val vside = vanillaSideMap(side)
if(block == Blocks.powered_repeater || block == Blocks.unpowered_repeater)//stupid minecraft hardcodes
{
val meta = world.getBlockMetadata(x, y, z)
if(vside == (meta & 3) || vside == Direction.rotateOpposite(meta & 3))
return if(power) 0x1F else 4
return 0
}
if(power || block.canConnectRedstone(world, x, y, z, vside))//some blocks accept power without visualising connections
return 0x1F
return 0 return 0
} }
if (
power || block.canConnectRedstone(world, x, y, z, vside)
) // some blocks accept power without visualising connections
return 0x1f
return 0
}
} }
@@ -0,0 +1,9 @@
package codechicken.multipart;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.world.IBlockAccess;
public interface ISBRHPart {
boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, RenderBlocks renderer);
}
@@ -8,47 +8,61 @@ import net.minecraft.entity.player.EntityPlayer
import net.minecraft.world.World import net.minecraft.world.World
import codechicken.lib.vec.BlockCoord import codechicken.lib.vec.BlockCoord
/** /** Java class implementation
* Java class implementation */
*/
abstract class JItemMultiPart extends Item with TItemMultiPart abstract class JItemMultiPart extends Item with TItemMultiPart
/** /** Simple multipart item class for easy placement. Simply override the newPart
* Simple multipart item class for easy placement. Simply override the newPart function and it the part will be added to the block space if it passes the occlusion tests. * function and it the part will be added to the block space if it passes the
*/ * occlusion tests.
trait TItemMultiPart extends Item */
{ trait TItemMultiPart extends Item {
def getHitDepth(vhit:Vector3, side:Int):Double = def getHitDepth(vhit: Vector3, side: Int): Double =
vhit.copy.scalarProject(Rotation.axes(side)) + (side%2^1) vhit.copy.scalarProject(Rotation.axes(side)) + (side % 2 ^ 1)
override def onItemUse(item:ItemStack, player:EntityPlayer, world:World, x:Int, y:Int, z:Int, side:Int, hitX:Float, hitY:Float, hitZ:Float):Boolean = override def onItemUse(
{ item: ItemStack,
val pos = new BlockCoord(x, y, z) player: EntityPlayer,
val vhit = new Vector3(hitX, hitY, hitZ) world: World,
val d = getHitDepth(vhit, side) x: Int,
y: Int,
z: Int,
side: Int,
hitX: Float,
hitY: Float,
hitZ: Float
): Boolean = {
val pos = new BlockCoord(x, y, z)
val vhit = new Vector3(hitX, hitY, hitZ)
val d = getHitDepth(vhit, side)
def place():Boolean = def place(): Boolean = {
{ val part = newPart(item, player, world, pos, side, vhit)
val part = newPart(item, player, world, pos, side, vhit) if (part == null || !TileMultipart.canPlacePart(world, pos, part))
if(part == null || !TileMultipart.canPlacePart(world, pos, part)) return false
return false
if(!world.isRemote) if (!world.isRemote)
TileMultipart.addPart(world, pos, part) TileMultipart.addPart(world, pos, part)
if(!player.capabilities.isCreativeMode) if (!player.capabilities.isCreativeMode)
item.stackSize-=1 item.stackSize -= 1
return true return true
}
if(d < 1 && place())
return true
pos.offset(side)
return place()
} }
/** if (d < 1 && place())
* Create a new part based on the placement information parameters. return true
*/
def newPart(item:ItemStack, player:EntityPlayer, world:World, pos:BlockCoord, side:Int, vhit:Vector3):TMultiPart pos.offset(side)
return place()
}
/** Create a new part based on the placement information parameters.
*/
def newPart(
item: ItemStack,
player: EntityPlayer,
world: World,
pos: BlockCoord,
side: Int,
vhit: Vector3
): TMultiPart
} }
@@ -0,0 +1,18 @@
package codechicken.multipart;
import net.minecraft.block.Block;
import net.minecraft.world.IBlockAccess;
public interface JsonModeledPart {
Block getBlock();
/**
* Use to give your part a world that can be used to define properties for rendering. For example having your world
* returning your block with some specific state such as meta you can override the getMeta for the input location to
* be the meta you desire
*
* @return The world to use
*/
IBlockAccess getRenderWorld();
}
@@ -15,225 +15,233 @@ import com.google.common.collect.ArrayListMultimap
import scala.collection.JavaConversions._ import scala.collection.JavaConversions._
import net.minecraft.nbt.NBTTagCompound import net.minecraft.nbt.NBTTagCompound
/** /** This class handles the registration and internal ID mapping of all multipart
* This class handles the registration and internal ID mapping of all multipart classes. * classes.
*/ */
object MultiPartRegistry object MultiPartRegistry {
{
/** /** Interface to be registered for constructing parts. Every instance of every
* Interface to be registered for constructing parts. * multipart is constructed from an implementor of this.
* Every instance of every multipart is constructed from an implementor of this. */
*/ @Deprecated
@Deprecated trait IPartFactory {
trait IPartFactory
{ /** Create a new instance of the part with the specified type name
/** * identifier
* Create a new instance of the part with the specified type name identifier * @param client
* @param client If the part instance is for the client or the server * If the part instance is for the client or the server
*/ */
def createPart(name: String, client: Boolean): TMultiPart def createPart(name: String, client: Boolean): TMultiPart
}
/** Will replace IPartFactory in 1.8
*/
trait IPartFactory2 {
/** Create a new server instance of the part with the specified type name
* identifier
* @param nbt
* The tag compound that will be passed to part.load, can be used to
* change the class of part returned
*/
def createPart(name: String, nbt: NBTTagCompound): TMultiPart
/** Create a new client instance of the part with the specified type name
* identifier
* @param packet
* The packet that will be passed to part.readDesc, can be used to change
* the class of part returned
*/
def createPart(name: String, packet: MCDataInput): TMultiPart
}
/** An interface for converting existing blocks/tile entities to multipart
* versions.
*/
trait IPartConverter {
/** Return true if this converter can handle the specific blockID (may or
* may not actually convert the block)
*/
def blockTypes: Iterable[Block]
/** Return a multipart version of the block at pos in world. Return null if
* no conversion is possible.
*/
def convert(world: World, pos: BlockCoord): TMultiPart
}
private val typeMap = MMap[String, IPartFactory2]()
private val nameMap = MMap[String, Int]()
private var idMap: Array[(String, IPartFactory2)] = _
private val idWriter = new IDWriter
private val converters = ArrayListMultimap.create[Block, IPartConverter]()
private val containers = MMap[String, ModContainer]()
/** The state of the registry. 0 = no parts, 1 = registering, 2 = registered
*/
private var state: Int = 0
/** Register a part factory with an array of types it is capable of
* instantiating. Must be called before postInit
* @deprecated
* Use IPartFactory2
*/
@Deprecated
def registerParts(partFactory: IPartFactory, types: Array[String]) {
registerParts(partFactory.createPart _, types: _*)
}
/** Scala function version of registerParts
* @deprecated
* Use IPartFactory2
*/
@Deprecated
def registerParts(
partFactory: (String, Boolean) => TMultiPart,
types: String*
) {
registerParts(
new IPartFactory2 {
override def createPart(name: String, packet: MCDataInput) =
partFactory(name, true)
override def createPart(name: String, nbt: NBTTagCompound) =
partFactory(name, false)
},
types: _*
)
}
/** Register a part factory with an array of types it is capable of
* instantiating. Must be called before postInit
*/
def registerParts(partFactory: IPartFactory2, types: Array[String]) {
registerParts(partFactory, types: _*)
}
/** Scala va-args version of registerParts
*/
def registerParts(partFactory: IPartFactory2, types: String*) {
if (loaded)
throw new IllegalStateException(
"Parts must be registered in the init methods."
)
state = 1
val container = Loader.instance.activeModContainer
if (container == null)
throw new IllegalStateException(
"Parts must be registered during the initialization phase of a mod container"
)
types.foreach { s =>
if (typeMap.contains(s))
throw new IllegalStateException(
"Part with id " + s + " is already registered."
)
typeMap.put(s, partFactory)
containers.put(s, container)
} }
}
/** /** Register a part converter instance
* Will replace IPartFactory in 1.8 */
*/ def registerConverter(c: IPartConverter) {
trait IPartFactory2 c.blockTypes.foreach(converters.put(_, c))
{ }
/**
* Create a new server instance of the part with the specified type name identifier
* @param nbt The tag compound that will be passed to part.load, can be used to change the class of part returned
*/
def createPart(name: String, nbt: NBTTagCompound): TMultiPart
/** private[multipart] def beforeServerStart() {
* Create a new client instance of the part with the specified type name identifier idMap = typeMap.toList.sortBy(_._1).toArray
* @param packet The packet that will be passed to part.readDesc, can be used to change the class of part returned idWriter.setMax(idMap.length)
*/ nameMap.clear()
def createPart(name: String, packet: MCDataInput): TMultiPart for (i <- 0 until idMap.length)
nameMap.put(idMap(i)._1, i)
}
private[multipart] def writeIDMap(packet: PacketCustom) {
packet.writeInt(idMap.length)
idMap.foreach(e => packet.writeString(e._1))
}
private[multipart] def readIDMap(packet: PacketCustom): Seq[String] = {
val k = packet.readInt()
idWriter.setMax(k)
idMap = new Array(k)
nameMap.clear()
val missing = ListBuffer[String]()
for (i <- 0 until k) {
val s = packet.readString()
val v = typeMap.get(s)
if (v.isEmpty)
missing += s
else {
idMap(i) = (s, v.get)
nameMap.put(s, i)
}
} }
return missing
}
/** /** Return true if any multiparts have been registered
* An interface for converting existing blocks/tile entities to multipart versions. */
*/ private[multipart] def required = state > 0
trait IPartConverter
{
/**
* Return true if this converter can handle the specific blockID (may or may not actually convert the block)
*/
def blockTypes: Iterable[Block]
/** /** Return true if no more parts can be registered
* Return a multipart version of the block at pos in world. Return null if no conversion is possible. */
*/ def loaded = state == 2
def convert(world: World, pos: BlockCoord): TMultiPart
private[multipart] def postInit() {
state = 2
}
/** Writes the id of part to data
*/
def writePartID(data: MCDataOutput, part: TMultiPart) {
idWriter.write(data, nameMap.get(part.getType).get)
}
/** Uses instantiators to creat a new part from the id read from data
*/
def readPart(data: MCDataInput) = {
val e = idMap(idWriter.read(data))
e._2.createPart(e._1, data)
}
/** Uses instantiators to creat a new part from the a tag compound
*/
def loadPart(name: String, nbt: NBTTagCompound) = typeMap.get(name) match {
case Some(factory) => factory.createPart(name, nbt)
case None =>
logger.error("Missing mapping for part with ID: " + name)
null
}
/** Uses instantiators to create a new part with specified identifier on side
* @deprecated
* currently calls the nbt/packet version with a null parameter, use
* readPart or loadPart instead
*/
@Deprecated
def createPart(name: String, client: Boolean) = typeMap.get(name) match {
case Some(factory) =>
if (client) factory.createPart(name, null: MCDataInput)
else factory.createPart(name, null: NBTTagCompound)
case None =>
logger.error("Missing mapping for part with ID: " + name)
null
}
/** Calls converters to create a multipart version of the block at pos
*/
def convertBlock(world: World, pos: BlockCoord, block: Block): TMultiPart = {
for (c <- converters.get(block)) {
val ret = c.convert(world, pos)
if (ret != null)
return ret
} }
return null
}
private val typeMap = MMap[String, IPartFactory2]() def getModContainer(name: String) = containers(name)
private val nameMap = MMap[String, Int]()
private var idMap: Array[(String, IPartFactory2)] = _
private val idWriter = new IDWriter
private val converters = ArrayListMultimap.create[Block, IPartConverter]()
private val containers = MMap[String, ModContainer]()
/**
* The state of the registry. 0 = no parts, 1 = registering, 2 = registered
*/
private var state: Int = 0
/**
* Register a part factory with an array of types it is capable of instantiating. Must be called before postInit
* @deprecated Use IPartFactory2
*/
@Deprecated
def registerParts(partFactory: IPartFactory, types: Array[String]) {
registerParts(partFactory.createPart _, types: _*)
}
/**
* Scala function version of registerParts
* @deprecated Use IPartFactory2
*/
@Deprecated
def registerParts(partFactory: (String, Boolean) => TMultiPart, types: String*) {
registerParts(new IPartFactory2 {
override def createPart(name: String, packet: MCDataInput) = partFactory(name, true)
override def createPart(name: String, nbt: NBTTagCompound) = partFactory(name, false)
}, types:_*)
}
/**
* Register a part factory with an array of types it is capable of instantiating. Must be called before postInit
*/
def registerParts(partFactory: IPartFactory2, types: Array[String]) {
registerParts(partFactory, types:_*)
}
/**
* Scala va-args version of registerParts
*/
def registerParts(partFactory: IPartFactory2, types: String*) {
if (loaded)
throw new IllegalStateException("Parts must be registered in the init methods.")
state = 1
val container = Loader.instance.activeModContainer
if (container == null)
throw new IllegalStateException("Parts must be registered during the initialization phase of a mod container")
types.foreach { s =>
if (typeMap.contains(s))
throw new IllegalStateException("Part with id " + s + " is already registered.")
logger.debug("Registered multipart: "+s)
typeMap.put(s, partFactory)
containers.put(s, container)
}
}
/**
* Register a part converter instance
*/
def registerConverter(c: IPartConverter) {
c.blockTypes.foreach(converters.put(_, c))
}
private[multipart] def beforeServerStart() {
idMap = typeMap.toList.sortBy(_._1).toArray
idWriter.setMax(idMap.length)
nameMap.clear()
for (i <- 0 until idMap.length)
nameMap.put(idMap(i)._1, i)
}
private[multipart] def writeIDMap(packet: PacketCustom) {
packet.writeInt(idMap.length)
idMap.foreach(e => packet.writeString(e._1))
}
private[multipart] def readIDMap(packet: PacketCustom): Seq[String] = {
val k = packet.readInt()
idWriter.setMax(k)
idMap = new Array(k)
nameMap.clear()
val missing = ListBuffer[String]()
for (i <- 0 until k) {
val s = packet.readString()
val v = typeMap.get(s)
if (v.isEmpty)
missing += s
else {
idMap(i) = (s, v.get)
nameMap.put(s, i)
}
}
return missing
}
/**
* Return true if any multiparts have been registered
*/
private[multipart] def required = state > 0
/**
* Return true if no more parts can be registered
*/
def loaded = state == 2
private[multipart] def postInit() {
state = 2
}
/**
* Writes the id of part to data
*/
def writePartID(data: MCDataOutput, part: TMultiPart) {
idWriter.write(data, nameMap.get(part.getType).get)
}
/**
* Uses instantiators to creat a new part from the id read from data
*/
def readPart(data: MCDataInput) = {
val e = idMap(idWriter.read(data))
e._2.createPart(e._1, data)
}
/**
* Uses instantiators to creat a new part from the a tag compound
*/
def loadPart(name: String, nbt:NBTTagCompound) = typeMap.get(name) match {
case Some(factory) => factory.createPart(name, nbt)
case None =>
logger.error("Missing mapping for part with ID: " + name)
null
}
/**
* Uses instantiators to create a new part with specified identifier on side
* @deprecated currently calls the nbt/packet version with a null parameter, use readPart or loadPart instead
*/
@Deprecated
def createPart(name: String, client: Boolean) = typeMap.get(name) match {
case Some(factory) =>
if(client) factory.createPart(name, null: MCDataInput)
else factory.createPart(name, null: NBTTagCompound)
case None =>
logger.error("Missing mapping for part with ID: " + name)
null
}
/**
* Calls converters to create a multipart version of the block at pos
*/
def convertBlock(world: World, pos: BlockCoord, block: Block): TMultiPart = {
for (c <- converters.get(block)) {
val ret = c.convert(world, pos)
if (ret != null)
return ret
}
return null
}
def getModContainer(name: String) = containers(name)
} }
@@ -11,176 +11,229 @@ import scala.collection.mutable.Map
import codechicken.multipart.asm.{ScratchBitSet, MultipartMixinFactory} import codechicken.multipart.asm.{ScratchBitSet, MultipartMixinFactory}
import codechicken.multipart.asm.ASMImplicits._ import codechicken.multipart.asm.ASMImplicits._
/** /** This class manages the dynamic construction and allocation of container
* This class manages the dynamic construction and allocation of container TileMultipart instances. * TileMultipart instances.
* *
* Classes that extend TileMultipart, adding tile centric logic, optimisations or interfaces, can be registered to a marker interface on a part instance. * Classes that extend TileMultipart, adding tile centric logic, optimisations
* When a part is added to the tile that implements the certain marker interface, the container tile will be replaced with a class that includes the functionality from the corresponding mixin class. * or interfaces, can be registered to a marker interface on a part instance.
* * When a part is added to the tile that implements the certain marker
* Classes are generated in a similar fashion to the way scala traits are compiled. To see the output, simply enable the config option and look in the asm/multipart folder of you .minecraft directory. * interface, the container tile will be replaced with a class that includes
* * the functionality from the corresponding mixin class.
* There are several mixin traits that come with the API included in the scalatraits package. TPartialOcclusionTile is defined as class instead of trait to give an example for Java programmers. *
*/ * Classes are generated in a similar fashion to the way scala traits are
object MultipartGenerator extends ScratchBitSet * compiled. To see the output, simply enable the config option and look in the
{ * asm/multipart folder of you .minecraft directory.
private val tileTraitMap = Map[Class[_], BitSet]() *
private val interfaceTraitMap_c = Map[String, String]() * There are several mixin traits that come with the API included in the
private val interfaceTraitMap_s = Map[String, String]() * scalatraits package. TPartialOcclusionTile is defined as class instead of
private val partTraitMap_c = Map[Class[_], BitSet]() * trait to give an example for Java programmers.
private val partTraitMap_s = Map[Class[_], BitSet]() */
private val clientTraitId = MultipartMixinFactory.registerTrait(classOf[TileMultipartClient]) object MultipartGenerator extends ScratchBitSet {
private val tileTraitMap = Map[Class[_], BitSet]()
private val interfaceTraitMap_c = Map[String, String]()
private val interfaceTraitMap_s = Map[String, String]()
private val partTraitMap_c = Map[Class[_], BitSet]()
private val partTraitMap_s = Map[Class[_], BitSet]()
private val clientTraitId =
MultipartMixinFactory.registerTrait(classOf[TileMultipartClient])
private def partTraitMap(client:Boolean) = if(client) partTraitMap_c else partTraitMap_s private def partTraitMap(client: Boolean) =
private def interfaceTraitMap(client:Boolean) = if(client) interfaceTraitMap_c else interfaceTraitMap_s if (client) partTraitMap_c else partTraitMap_s
private def interfaceTraitMap(client: Boolean) =
if (client) interfaceTraitMap_c else interfaceTraitMap_s
private def traitsForPart(part:TMultiPart, client:Boolean) = private def traitsForPart(part: TMultiPart, client: Boolean) =
partTraitMap(client).getOrElseUpdate(part.getClass, { partTraitMap(client).getOrElseUpdate(
def heirachy(clazz:Class[_]):Seq[Class[_]] = part.getClass, {
{ def heirachy(clazz: Class[_]): Seq[Class[_]] = {
var superClasses:Seq[Class[_]] = clazz.getInterfaces.flatMap(c => heirachy(c)):+clazz var superClasses: Seq[Class[_]] =
if(clazz.getSuperclass != null) clazz.getInterfaces.flatMap(c => heirachy(c)) :+ clazz
superClasses = superClasses++heirachy(clazz.getSuperclass) if (clazz.getSuperclass != null)
return superClasses superClasses = superClasses ++ heirachy(clazz.getSuperclass)
} return superClasses
}
val map = interfaceTraitMap(client) val map = interfaceTraitMap(client)
val traits = heirachy(part.getClass).flatMap(c => map.get(c.nodeName)).distinct val traits =
heirachy(part.getClass).flatMap(c => map.get(c.nodeName)).distinct
val bitset = new BitSet val bitset = new BitSet
traits.map(MultipartMixinFactory.getId).foreach(bitset.set) traits.map(MultipartMixinFactory.getId).foreach(bitset.set)
bitset
})
private def setTraits(part:TMultiPart, client:Boolean):BitSet = setTraits(Seq(part), client)
private def setTraits(parts:Iterable[TMultiPart], client:Boolean) = {
val bitset = freshBitSet
parts.foreach(p => bitset.or(traitsForPart(p, client)))
if(client) bitset.set(clientTraitId)
bitset bitset
}
)
private def setTraits(part: TMultiPart, client: Boolean): BitSet =
setTraits(Seq(part), client)
private def setTraits(parts: Iterable[TMultiPart], client: Boolean) = {
val bitset = freshBitSet
parts.foreach(p => bitset.or(traitsForPart(p, client)))
if (client) bitset.set(clientTraitId)
bitset
}
/** Check if part adds any new interfaces to tile, if so, replace tile with a
* new copy and call tile.addPart(part) returns true if tile was replaced
*/
private[multipart] def addPart(
world: World,
pos: BlockCoord,
part: TMultiPart
): TileMultipart = {
val (tile, converted) = TileMultipart.getOrConvertTile2(world, pos)
val bitset = setTraits(part, world.isRemote)
var ntile = tile
if (ntile != null) {
if (converted) { // perform client conversion
ntile.partList(0).invalidateConvertedTile()
world.setBlock(pos.x, pos.y, pos.z, MultipartProxy.block, 0, 0)
silentAddTile(world, pos, ntile)
PacketCustom.sendToChunk(
new S23PacketBlockChange(pos.x, pos.y, pos.z, world),
world,
pos.x >> 4,
pos.z >> 4
)
ntile.partList(0).onConverted()
ntile.writeAddPart(ntile.partList(0))
}
val tileTraits = tileTraitMap(tile.getClass)
bitset.andNot(tileTraits)
if (!bitset.isEmpty) {
bitset.or(tileTraits)
ntile = MultipartMixinFactory.construct(bitset)
tile.setValid(false)
silentAddTile(world, pos, ntile)
ntile.from(tile)
}
} else {
world.setBlock(pos.x, pos.y, pos.z, MultipartProxy.block, 0, 0)
ntile = MultipartMixinFactory.construct(bitset)
silentAddTile(world, pos, ntile)
} }
ntile.addPart_impl(part)
return ntile
}
/** /** Adds a tile entity to the world without notifying neighbor blocks or
* Check if part adds any new interfaces to tile, if so, replace tile with a new copy and call tile.addPart(part) * adding it to the tick list
* returns true if tile was replaced */
*/ def silentAddTile(world: World, pos: BlockCoord, tile: TileEntity) {
private[multipart] def addPart(world:World, pos:BlockCoord, part:TMultiPart):TileMultipart = tile.xCoord = pos.x;
{ tile.yCoord = pos.y;
val (tile, converted) = TileMultipart.getOrConvertTile2(world, pos) tile.zCoord = pos.z;
val bitset = setTraits(part, world.isRemote)
var ntile = tile val chunk = world.getChunkFromBlockCoords(pos.x, pos.z)
if(ntile != null) { if (chunk != null) {
if(converted) {//perform client conversion chunk.addTileEntity(tile)
ntile.partList(0).invalidateConvertedTile()
world.setBlock(pos.x, pos.y, pos.z, MultipartProxy.block, 0, 0)
silentAddTile(world, pos, ntile)
PacketCustom.sendToChunk(new S23PacketBlockChange(pos.x, pos.y, pos.z, world), world, pos.x>>4, pos.z>>4)
ntile.partList(0).onConverted()
ntile.writeAddPart(ntile.partList(0))
}
val tileTraits = tileTraitMap(tile.getClass)
bitset.andNot(tileTraits)
if(!bitset.isEmpty) {
bitset.or(tileTraits)
ntile = MultipartMixinFactory.construct(bitset)
tile.setValid(false)
silentAddTile(world, pos, ntile)
ntile.from(tile)
}
}
else {
world.setBlock(pos.x, pos.y, pos.z, MultipartProxy.block, 0, 0)
ntile = MultipartMixinFactory.construct(bitset)
silentAddTile(world, pos, ntile)
}
ntile.addPart_impl(part)
return ntile
} }
}
/** /** Check if tile satisfies all the interfaces required by parts. If not,
* Adds a tile entity to the world without notifying neighbor blocks or adding it to the tick list * return a new generated copy of tile
*/ */
def silentAddTile(world:World, pos:BlockCoord, tile:TileEntity) { private[multipart] def generateCompositeTile(
val chunk = world.getChunkFromBlockCoords(pos.x, pos.z) tile: TileEntity,
if(chunk != null) parts: Iterable[TMultiPart],
chunk.func_150812_a(pos.x & 15, pos.y, pos.z & 15, tile) client: Boolean
) = {
val bitset = setTraits(parts, client)
if (
tile != null && tile
.isInstanceOf[TileMultipart] && bitset == tileTraitMap(tile.getClass)
)
tile.asInstanceOf[TileMultipart]
else
MultipartMixinFactory.construct(bitset)
}
/** Check if there are any redundant interfaces on tile, if so, replace tile
* with new copy
*/
private[multipart] def partRemoved(tile: TileMultipart) = {
val ntile =
generateCompositeTile(tile, tile.partList, tile.getWorldObj.isRemote)
if (ntile != tile) {
tile.setValid(false)
silentAddTile(tile.getWorldObj, new BlockCoord(tile), ntile)
ntile.from(tile)
ntile.notifyTileChange()
} }
ntile
}
/** /** register s_trait to be applied to tiles containing parts implementing
* Check if tile satisfies all the interfaces required by parts. If not, return a new generated copy of tile * s_interface
*/ */
private[multipart] def generateCompositeTile(tile:TileEntity, parts:Iterable[TMultiPart], client:Boolean) = { def registerTrait(s_interface: String, s_trait: String): Unit =
val bitset = setTraits(parts, client) registerTrait(s_interface, s_trait, s_trait)
if(tile != null && tile.isInstanceOf[TileMultipart] && bitset == tileTraitMap(tile.getClass))
tile.asInstanceOf[TileMultipart] /** register traits to be applied to tiles containing parts implementing
else * s_interface c_trait for client worlds (may be null) s_trait for server
MultipartMixinFactory.construct(bitset) * worlds (may be null)
*/
def registerTrait(
s_interface$ : String,
c_trait$ : String,
s_trait$ : String
) {
val s_interface = nodeName(s_interface$)
val c_trait = nodeName(c_trait$)
val s_trait = nodeName(s_trait$)
def registerSide(map: Map[String, String], traitName: String) = if (
traitName != null
) {
if (map.contains(s_interface))
logger.error("Trait already registered for " + s_interface)
else {
map.put(s_interface, traitName)
MultipartMixinFactory.registerTrait(traitName)
}
} }
registerSide(interfaceTraitMap_c, c_trait)
registerSide(interfaceTraitMap_s, s_trait)
}
/** def registerPassThroughInterface(s_interface: String): Unit =
* Check if there are any redundant interfaces on tile, if so, replace tile with new copy registerPassThroughInterface(s_interface, true, true)
*/
private[multipart] def partRemoved(tile:TileMultipart) = {
val ntile = generateCompositeTile(tile, tile.partList, tile.getWorldObj.isRemote)
if(ntile != tile) {
tile.setValid(false)
silentAddTile(tile.getWorldObj, new BlockCoord(tile), ntile)
ntile.from(tile)
ntile.notifyTileChange()
}
ntile
}
/** /** A passthrough interface, is an interface to be implemented on the
* register s_trait to be applied to tiles containing parts implementing s_interface * container tile instance, for which all calls are passed directly to the
*/ * single implementing part. Registering a passthrough interface is
def registerTrait(s_interface:String, s_trait:String):Unit = registerTrait(s_interface, s_trait, s_trait) * equivalent to defining a mixin class as follows.
* 1. field 'impl' which contains the reference to the corresponding part
* 2. occlusionTest is overriden to prevent more than one part with
* s_interface existing in the block space 3. implementing s_interface
* and passing all calls directly to the part instance.
*
* This allows compatibility with APIs that expect interfaces on the tile
* entity.
*/
def registerPassThroughInterface(
s_interface: String,
client: Boolean,
server: Boolean
) {
val tType = MultipartMixinFactory.generatePassThroughTrait(s_interface)
if (tType == null)
return
/** registerTrait(
* register traits to be applied to tiles containing parts implementing s_interface s_interface,
* c_trait for client worlds (may be null) if (client) tType else null,
* s_trait for server worlds (may be null) if (server) tType else null
*/ )
def registerTrait(s_interface$:String, c_trait$:String, s_trait$:String) { }
val s_interface = nodeName(s_interface$)
val c_trait = nodeName(c_trait$)
val s_trait = nodeName(s_trait$)
def registerSide(map:Map[String, String], traitName:String) = if(traitName != null) { private[multipart] def registerTileClass(
if(map.contains(s_interface)) clazz: Class[_ <: TileMultipart],
logger.error("Trait already registered for "+s_interface) traits: BitSet
else { ) {
map.put(s_interface, traitName) tileTraitMap.put(clazz, traits.copy)
MultipartMixinFactory.registerTrait(traitName) MultipartProxy.onTileClassBuilt(clazz)
} }
}
registerSide(interfaceTraitMap_c, c_trait)
registerSide(interfaceTraitMap_s, s_trait)
}
def registerPassThroughInterface(s_interface:String):Unit = registerPassThroughInterface(s_interface, true, true)
/**
* A passthrough interface, is an interface to be implemented on the container tile instance, for which all calls are passed directly to the single implementing part.
* Registering a passthrough interface is equivalent to defining a mixin class as follows.
* 1. field 'impl' which contains the reference to the corresponding part
* 2. occlusionTest is overriden to prevent more than one part with s_interface existing in the block space
* 3. implementing s_interface and passing all calls directly to the part instance.
*
* This allows compatibility with APIs that expect interfaces on the tile entity.
*/
def registerPassThroughInterface(s_interface:String, client:Boolean, server:Boolean) {
val tType = MultipartMixinFactory.generatePassThroughTrait(s_interface)
if(tType == null)
return
registerTrait(s_interface, if(client) tType else null, if(server) tType else null)
}
private[multipart] def registerTileClass(clazz:Class[_ <: TileMultipart], traits:BitSet) {
tileTraitMap.put(clazz, traits.copy)
MultipartProxy.onTileClassBuilt(clazz)
}
} }
@@ -12,47 +12,50 @@ import net.minecraft.world.WorldServer
import java.util.Arrays import java.util.Arrays
import java.lang.Iterable import java.lang.Iterable
/** /** Static helper class for handling the unusual way that multipart tile
* Static helper class for handling the unusual way that multipart tile entities load from nbt and send description packets * entities load from nbt and send description packets <br> Multipart tile
* <br> * entities will all save themselves with the id "savedMultipart" which if
* Multipart tile entities will all save themselves with the id "savedMultipart" which if normally loaded by minecraft, * normally loaded by minecraft, will create a dummy tile entity which just
* will create a dummy tile entity which just holds the NBT it was read from. These dummies are then converted to actual container tiles on the ChunkLoad event. * holds the NBT it was read from. These dummies are then converted to actual
* The createTileFromNBT function should be used to construct a multipart tile from NBT without the ChunkLoad event. * container tiles on the ChunkLoad event. The createTileFromNBT function
* <br> * should be used to construct a multipart tile from NBT without the ChunkLoad
* Multipart tile entities do not send description packets via the conventional means of one packet per tile when PlayerInstance calls for it, to do so would be terribly inefficient. * event. <br> Multipart tile entities do not send description packets via the
* Instead, the ChunkWatch event is used to batch all the describing data for a chunk into one packet which is compressed using relative positions. * conventional means of one packet per tile when PlayerInstance calls for it,
* The sendDescPacket(s) functions should be used to send the description packet of a tile or tiles without a ChunkWatch event. * to do so would be terribly inefficient. Instead, the ChunkWatch event is
* <br> * used to batch all the describing data for a chunk into one packet which is
* An example of using this class to move blocks/tile entites around can be found at www.chickenbones.craftsaddle.org/Files/Other/ItemDevTool2.java * compressed using relative positions. The sendDescPacket(s) functions should
*/ * be used to send the description packet of a tile or tiles without a
object MultipartHelper * ChunkWatch event. <br> An example of using this class to move blocks/tile
{ * entites around can be found at
/*val f_playersInChunk = classOf[PlayerInstance].getDeclaredField( * www.chickenbones.craftsaddle.org/Files/Other/ItemDevTool2.java
*/
object MultipartHelper {
/*val f_playersInChunk = classOf[PlayerInstance].getDeclaredField(
new ObfMapping("net/minecraft/server/management/PlayerInstance", "playersInChunk", "Ljava/util/List;") new ObfMapping("net/minecraft/server/management/PlayerInstance", "playersInChunk", "Ljava/util/List;")
.toRuntime.s_name) .toRuntime.s_name)
f_playersInChunk.setAccessible(true) f_playersInChunk.setAccessible(true)
def playersInChunk(inst:PlayerInstance) = f_playersInChunk.get(inst).asInstanceOf[List[_]]*/ def playersInChunk(inst:PlayerInstance) = f_playersInChunk.get(inst).asInstanceOf[List[_]]*/
def createTileFromNBT(world:World, tag:NBTTagCompound):TileEntity = { def createTileFromNBT(world: World, tag: NBTTagCompound): TileEntity = {
if(!tag.getString("id").equals("savedMultipart")) if (!tag.getString("id").equals("savedMultipart"))
return null return null
MultipartSaveLoad.loadingWorld = world MultipartSaveLoad.loadingWorld = world
return TileMultipart.createFromNBT(tag) return TileMultipart.createFromNBT(tag)
} }
/** /** Note. This method should only be used to send tiles that have been created
* Note. This method should only be used to send tiles that have been created on the server mid-game via an NBT load to clients. * on the server mid-game via an NBT load to clients.
*/ */
def sendDescPacket(world:World, tile:TileEntity) { def sendDescPacket(world: World, tile: TileEntity) {
val c = world.getChunkFromBlockCoords(tile.xCoord, tile.zCoord) val c = world.getChunkFromBlockCoords(tile.xCoord, tile.zCoord)
val pkt = MultipartSPH.getDescPacket(c, Arrays.asList(tile).iterator) val pkt = MultipartSPH.getDescPacket(c, Arrays.asList(tile).iterator)
if(pkt != null) if (pkt != null)
pkt.sendToChunk(world, c.xPosition, c.zPosition) pkt.sendToChunk(world, c.xPosition, c.zPosition)
} }
/* Removed for compilation until PlayerInstance access transformer is pulled in forge /* Removed for compilation until PlayerInstance access transformer is pulled in forge
def sendDescPackets(world:World, tiles:Iterable[TileEntity]) { def sendDescPackets(world:World, tiles:Iterable[TileEntity]) {
val map = LinkedListMultimap.create[Long, TileEntity]() val map = LinkedListMultimap.create[Long, TileEntity]()
tiles.filter(_.isInstanceOf[TileMultipart]).foreach(t => map.put(t.xCoord.toLong<<32|t.zCoord, t)) tiles.filter(_.isInstanceOf[TileMultipart]).foreach(t => map.put(t.xCoord.toLong<<32|t.zCoord, t))
@@ -68,40 +71,42 @@ object MultipartHelper
} }
}*/ }*/
/** /** Helper class for converting tile entities to multiparts on chunk load
* Helper class for converting tile entities to multiparts on chunk load */
*/ abstract class IPartTileConverter[T <: TileEntity](val clazz: Class[T]) {
abstract class IPartTileConverter[T <: TileEntity](val clazz:Class[T])
{
/**
* @return true if this tile can be converted by this converter. If canConvert returns true, but convertMulti returns no parts, the tile will be deleted
*/
def canConvert(tile:TileEntity) = clazz.isInstance(tile)
def convert(tile:TileEntity) = convertMulti(tile.asInstanceOf[T]) /** @return
* true if this tile can be converted by this converter. If canConvert
* returns true, but convertMulti returns no parts, the tile will be
* deleted
*/
def canConvert(tile: TileEntity) = clazz.isInstance(tile)
/** def convert(tile: TileEntity) = convertMulti(tile.asInstanceOf[T])
* Convert the TileEntity into multiple parts
* @return An iterable list of parts or an empty list to delete the tile /** Convert the TileEntity into multiple parts
*/ * @return
def convertMulti(tile:T):Iterable[TMultiPart] = convertOne(tile) match { * An iterable list of parts or an empty list to delete the tile
case null => Seq() */
case p => Seq(p) def convertMulti(tile: T): Iterable[TMultiPart] = convertOne(tile) match {
} case null => Seq()
/** case p => Seq(p)
* Convert the TileEntity into a part
* @return The converted part, or null to delete the tile
*/
def convertOne(tile:T):TMultiPart
} }
def registerTileConverter(converter:IPartTileConverter[_]) { /** Convert the TileEntity into a part
MultipartSaveLoad.converters += converter * @return
} * The converted part, or null to delete the tile
*/
def convertOne(tile: T): TMultiPart
}
def createTileFromParts(parts:Iterable[TMultiPart]) = { def registerTileConverter(converter: IPartTileConverter[_]) {
val tile = MultipartGenerator.generateCompositeTile(null, parts, false) MultipartSaveLoad.converters += converter
tile.loadParts(parts) }
tile
} def createTileFromParts(parts: Iterable[TMultiPart]) = {
val tile = MultipartGenerator.generateCompositeTile(null, parts, false)
tile.loadParts(parts)
tile
}
} }
@@ -5,70 +5,91 @@ import codechicken.lib.vec.Vector3
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler
import cpw.mods.fml.client.registry.RenderingRegistry import cpw.mods.fml.client.registry.RenderingRegistry
import net.minecraft.block.Block import net.minecraft.block.Block
import net.minecraft.client.renderer.{Tessellator, RenderBlocks} import net.minecraft.client.renderer.{RenderBlocks, Tessellator}
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer
import net.minecraft.tileentity.TileEntity import net.minecraft.tileentity.TileEntity
import net.minecraft.world.IBlockAccess import net.minecraft.world.IBlockAccess
import net.minecraft.client.Minecraft import net.minecraftforge.client.MinecraftForgeClient
import cpw.mods.fml.relauncher.SideOnly import cpw.mods.fml.relauncher.SideOnly
import cpw.mods.fml.relauncher.Side import cpw.mods.fml.relauncher.Side
import codechicken.lib.raytracer.ExtendedMOP import codechicken.multipart.RenderPartResolver
import codechicken.lib.lighting.LightMatrix
/** /** Internal class for rendering callbacks. Should be moved to the handler
* Internal class for rendering callbacks. Should be moved to the handler package * package
*/ */
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
object MultipartRenderer extends TileEntitySpecialRenderer with ISimpleBlockRenderingHandler object MultipartRenderer
{ extends TileEntitySpecialRenderer
TileMultipart.renderID = RenderingRegistry.getNextAvailableRenderId with ISimpleBlockRenderingHandler {
var pass:Int = 0 TileMultipart.renderID = RenderingRegistry.getNextAvailableRenderId
override def renderTileEntityAt(t:TileEntity, x:Double, y:Double, z:Double, f:Float) override def renderTileEntityAt(
{ t: TileEntity,
val tmpart = t.asInstanceOf[TileMultipartClient] x: Double,
if(tmpart.partList.isEmpty) y: Double,
return z: Double,
f: Float
) {
val tmpart = t.asInstanceOf[TileMultipartClient]
if (tmpart.partList.isEmpty | !tmpart.hasDynamicParts)
return
CCRenderState.reset() val state = CCRenderState.instance
CCRenderState.pullLightmap() state.resetInstance()
CCRenderState.useNormals = true state.pullLightmapInstance()
state.useNormals = true
val pos = new Vector3(x, y, z) val pos = new Vector3(x, y, z)
tmpart.renderDynamic(pos, f, pass) tmpart.renderDynamic(pos, f, MinecraftForgeClient.getRenderPass)
} }
override def getRenderId = TileMultipart.renderID override def getRenderId = TileMultipart.renderID
override def renderWorldBlock(world:IBlockAccess, x:Int, y:Int, z:Int, block:Block, modelId:Int, renderer:RenderBlocks):Boolean = override def renderWorldBlock(
{ world: IBlockAccess,
val t = world.getTileEntity(x, y, z) x: Int,
if(!t.isInstanceOf[TileMultipartClient]) y: Int,
return false z: Int,
block: Block,
modelId: Int,
renderer: RenderBlocks
): Boolean = {
val t = world.getTileEntity(x, y, z)
if (!t.isInstanceOf[TileMultipartClient])
return false
val tmpart = t.asInstanceOf[TileMultipartClient] val tmpart = t.asInstanceOf[TileMultipartClient]
if(tmpart.partList.isEmpty) if (tmpart.partList.isEmpty)
return false return false
if(renderer.hasOverrideBlockTexture) if (renderer.hasOverrideBlockTexture) {
{ val part =
val hit = Minecraft.getMinecraft.objectMouseOver RenderPartResolver.resolve(world, x, y, z)
if(hit != null && hit.blockX == x && hit.blockY == y && hit.blockZ == z && ExtendedMOP.getData(hit).isInstanceOf[(_, _)]) if (part != null) {
{ part match {
val hitInfo:(Int, _) = ExtendedMOP.getData(hit) case isbrh: ISBRHPart =>
if(hitInfo._1.isInstanceOf[Int] && hitInfo._1 >= 0 && hitInfo._1 < tmpart.partList.size) isbrh.renderWorldBlock(world, x, y, z, renderer)
tmpart.partList(hitInfo._1).drawBreaking(renderer) case _ =>
} part.drawBreaking(renderer)
return false
} }
}
CCRenderState.reset() return false
CCRenderState.lightMatrix.locate(world, x, y, z)
return tmpart.renderStatic(new Vector3(x, y, z), pass)
} }
override def renderInventoryBlock(block:Block, meta:Int, modelId:Int, renderer:RenderBlocks) {} val state = CCRenderState.instance
state.resetInstance()
state.lightMatrix.locate(world, x, y, z)
val b = tmpart.renderStatic(world, new Vector3(x, y, z), renderer)
state.lightMatrix.access = null
b
}
override def renderInventoryBlock(
block: Block,
meta: Int,
modelId: Int,
renderer: RenderBlocks
) {}
def shouldRender3DInInventory(modelId:Int) = false def shouldRender3DInInventory(modelId: Int) = false
} }
@@ -4,79 +4,77 @@ import scala.collection.mutable.{Map => MMap}
import codechicken.lib.data.MCDataOutput import codechicken.lib.data.MCDataOutput
import codechicken.lib.data.MCDataInput import codechicken.lib.data.MCDataInput
/** /** Static class for packing update data. When a specific property of a part
* Static class for packing update data. * changes and needs sending to the client, a bit can be set in the mask. This
* When a specific property of a part changes and needs sending to the client, a bit can be set in the mask. * bit can then be checked in the writeScheduled callback. This prevents
* This bit can then be checked in the writeScheduled callback. * sending multiple packets if the same property updates more than once per
* This prevents sending multiple packets if the same property updates more than once per tick. * tick.
*/ */
object PacketScheduler object PacketScheduler {
{ private val map = MMap[TMultiPart, Long]()
private val map = MMap[TMultiPart, Long]()
/** /** Add bits to the current update mask for part. (binary OR)
* Add bits to the current update mask for part. (binary OR) */
*/ def schedulePacket(part: TMultiPart, mask: Long) {
def schedulePacket(part:TMultiPart, mask:Long) { if (part.world.isRemote)
if(part.world.isRemote) throw new IllegalArgumentException(
throw new IllegalArgumentException("Cannot use PacketScheduler on a client world") "Cannot use PacketScheduler on a client world"
)
map.put(part, map.getOrElse(part, 0L)|mask) map.put(part, map.getOrElse(part, 0L) | mask)
} }
private[multipart] def sendScheduled() { private[multipart] def sendScheduled() {
map.foreach{ e => map.foreach { e =>
val (part, mask) = e val (part, mask) = e
if(part.tile != null) { if (part.tile != null) {
val ipart = part.asInstanceOf[IScheduledPacketPart] val ipart = part.asInstanceOf[IScheduledPacketPart]
val w = part.getWriteStream val w = part.getWriteStream
ipart.maskWidth match { ipart.maskWidth match {
case 1 => w.writeByte(mask.toInt) case 1 => w.writeByte(mask.toInt)
case 2 => w.writeShort(mask.toInt) case 2 => w.writeShort(mask.toInt)
case 4 => w.writeInt(mask.toInt) case 4 => w.writeInt(mask.toInt)
case 8 => w.writeLong(mask) case 8 => w.writeLong(mask)
}
ipart.writeScheduled(mask, w)
}
} }
map.clear()
ipart.writeScheduled(mask, w)
}
} }
map.clear()
}
} }
/** /** Callback interface for PacketScheduler
* Callback interface for PacketScheduler */
*/ trait IScheduledPacketPart {
trait IScheduledPacketPart
{
/**
* Write scheduled data to the packet, mask is the cumulative mask from calls to schedulePacket
*/
def writeScheduled(mask:Long, packet:MCDataOutput)
/** /** Write scheduled data to the packet, mask is the cumulative mask from calls
* Returns the width (in bytes) of the data type required to hold all valid mask bits. Valid values are 1, 2, 4 and 8 * to schedulePacket
*/ */
def maskWidth:Int def writeScheduled(mask: Long, packet: MCDataOutput)
/** /** Returns the width (in bytes) of the data type required to hold all valid
* Read data matching mask. Estiablishes a method for subclasses to override. This should be called from read * mask bits. Valid values are 1, 2, 4 and 8
*/ */
def readScheduled(mask:Long, packet:MCDataInput) def maskWidth: Int
/** Read data matching mask. Estiablishes a method for subclasses to override.
* This should be called from read
*/
def readScheduled(mask: Long, packet: MCDataInput)
} }
trait TScheduledPacketPart extends TMultiPart with IScheduledPacketPart trait TScheduledPacketPart extends TMultiPart with IScheduledPacketPart {
{ final override def read(packet: MCDataInput) {
final override def read(packet:MCDataInput) { val mask = maskWidth match {
val mask = maskWidth match { case 1 => packet.readUByte
case 1 => packet.readUByte case 2 => packet.readUShort
case 2 => packet.readUShort case 4 => packet.readInt
case 4 => packet.readInt case 8 => packet.readLong
case 8 => packet.readLong
}
readScheduled(mask, packet)
} }
readScheduled(mask, packet)
}
def writeScheduled(mask:Long, packet:MCDataOutput){} def writeScheduled(mask: Long, packet: MCDataOutput) {}
def readScheduled(mask:Long, packet:MCDataInput){} def readScheduled(mask: Long, packet: MCDataInput) {}
} }
@@ -1,11 +1,11 @@
package codechicken.multipart; package codechicken.multipart;
/** /**
* Defines what each slot in a multipart tile corresponds to and provides some utility functions. * Defines what each slot in a multipart tile corresponds to and provides some utility functions. For performance
* For performance reasons, it is recommended that integer constants be useds as opposed to this enum * reasons, it is recommended that integer constants be useds as opposed to this enum
*/ */
public enum PartMap public enum PartMap {
{
BOTTOM(0), BOTTOM(0),
TOP(1), TOP(1),
NORTH(2), NORTH(2),
@@ -13,122 +13,115 @@ public enum PartMap
WEST(4), WEST(4),
EAST(5), EAST(5),
CENTER(6), CENTER(6),
CORNER_NNN(7),//0 CORNER_NNN(7), // 0
CORNER_NPN(8),//1 CORNER_NPN(8), // 1
CORNER_NNP(9),//2 CORNER_NNP(9), // 2
CORNER_NPP(10),//3 CORNER_NPP(10), // 3
CORNER_PNN(11),//4 CORNER_PNN(11), // 4
CORNER_PPN(12),//5 CORNER_PPN(12), // 5
CORNER_PNP(13),//6 CORNER_PNP(13), // 6
CORNER_PPP(14),//7 CORNER_PPP(14), // 7
EDGE_NYN(15),//0 EDGE_NYN(15), // 0
EDGE_NYP(16),//1 EDGE_NYP(16), // 1
EDGE_PYN(17),//2 EDGE_PYN(17), // 2
EDGE_PYP(18),//3 EDGE_PYP(18), // 3
EDGE_NNZ(19),//4 EDGE_NNZ(19), // 4
EDGE_PNZ(20),//5 EDGE_PNZ(20), // 5
EDGE_NPZ(21),//6 EDGE_NPZ(21), // 6
EDGE_PPZ(22),//7 EDGE_PPZ(22), // 7
EDGE_XNN(23),//8 EDGE_XNN(23), // 8
EDGE_XPN(24),//9 EDGE_XPN(24), // 9
EDGE_XNP(25),//10 EDGE_XNP(25), // 10
EDGE_XPP(26);//11 EDGE_XPP(26); // 11
public final int i; public final int i;
public final int mask; public final int mask;
private PartMap(int i) private PartMap(int i) {
{
this.i = i; this.i = i;
mask = 1<<i; mask = 1 << i;
} }
/** /**
* Don't actually use this. * Don't actually use this.
*/ */
public static PartMap face(int i) public static PartMap face(int i) {
{
return values()[i]; return values()[i];
} }
/** /**
* Don't actually use this. * Don't actually use this.
*/ */
public static PartMap edge(int i) public static PartMap edge(int i) {
{ return values()[i + 15];
return values()[i+15];
} }
/** /**
* Don't actually use this. * Don't actually use this.
*/ */
public static PartMap corner(int i) public static PartMap corner(int i) {
{ return values()[i + 7];
return values()[i+7];
} }
/** /**
* Returns a 3 bit mask of the axis xzy that are variable in this edge. * Returns a 3 bit mask of the axis xzy that are variable in this edge. For example, the first 4 edges (15-18) are
* For example, the first 4 edges (15-18) are along the Y axis, variable in x and z, so the mask is 110b. Note axis y is 1<<0, z is 1<<1 and x is 1<<2 * along the Y axis, variable in x and z, so the mask is 110b. Note axis y is 1<<0, z is 1<<1 and x is 1<<2 Note the
* Note the parameter e is relative to the first edge slot and can range from 0-11 * parameter e is relative to the first edge slot and can range from 0-11
*/ */
public static int edgeAxisMask(int e) public static int edgeAxisMask(int e) {
{ switch (e >> 2) {
switch(e>>2) case 0:
{ return 6;
case 0: return 6; case 1:
case 1: return 5; return 5;
case 2: return 3; case 2:
return 3;
} }
throw new IllegalArgumentException("Switch Falloff"); throw new IllegalArgumentException("Switch Falloff");
} }
/** /**
* Unpacks an edge index, to a mask where high values indicate positive positions in that axis. * Unpacks an edge index, to a mask where high values indicate positive positions in that axis. Note the parameter e
* Note the parameter e is relative to the first edge slot and can range from 0-11 * is relative to the first edge slot and can range from 0-11 For example, edge 1 (slot 16), is EDGE_NYP so the mask
* For example, edge 1 (slot 16), is EDGE_NYP so the mask returned would be 010 as z is positive. * returned would be 010 as z is positive.
*/ */
public static int unpackEdgeBits(int e) public static int unpackEdgeBits(int e) {
{ switch (e >> 2) {
switch(e>>2) case 0:
{ return (e & 3) << 1;
case 0: return (e&3)<<1; case 1:
case 1: return (e&2)>>1|(e&1)<<2; return (e & 2) >> 1 | (e & 1) << 2;
case 2: return (e&3); case 2:
return (e & 3);
} }
throw new IllegalArgumentException("Switch Falloff"); throw new IllegalArgumentException("Switch Falloff");
} }
/** /**
* Repacks a mask of axis bits indicating positive positions, into an edge in along the same axis as e. * Repacks a mask of axis bits indicating positive positions, into an edge in along the same axis as e. Note the
* Note the parameter e is relative to the first edge slot and can range from 0-11 * parameter e is relative to the first edge slot and can range from 0-11
*/ */
public static int packEdgeBits(int e, int bits) public static int packEdgeBits(int e, int bits) {
{ switch (e >> 2) {
switch(e>>2) case 0:
{ return e & 0xC | bits >> 1;
case 0: return e&0xC|bits>>1; case 1:
case 1: return e&0xC|(bits&4)>>2|(bits&1)<<1; return e & 0xC | (bits & 4) >> 2 | (bits & 1) << 1;
case 2: return e&0xC|bits&3; case 2:
return e & 0xC | bits & 3;
} }
throw new IllegalArgumentException("Switch Falloff"); throw new IllegalArgumentException("Switch Falloff");
} }
private static int[] edgeBetweenMap = new int[]{ private static int[] edgeBetweenMap = new int[] { -1, -1, 8, 10, 4, 5, -1, -1, 9, 11, 6, 7, -1, -1, -1, -1, 0, 2,
-1, -1, 8, 10, 4, 5, -1, -1, -1, -1, 1, 3 };
-1, -1, 9, 11, 6, 7,
-1, -1,-1, -1, 0, 2,
-1, -1,-1, -1, 1, 3};
/** /**
* Returns the slot of the edge between 2 sides. * Returns the slot of the edge between 2 sides.
*/ */
public static int edgeBetween(int s1, int s2) public static int edgeBetween(int s1, int s2) {
{ if (s2 < s1) return edgeBetween(s2, s1);
if(s2 < s1) if ((s1 & 6) == (s2 & 6)) throw new IllegalArgumentException("Faces " + s1 + " and " + s2 + " are opposites");
return edgeBetween(s2, s1); return 15 + edgeBetweenMap[s1 * 6 + s2];
if((s1&6) == (s2&6))
throw new IllegalArgumentException("Faces "+s1+" and "+s2+" are opposites");
return 15+edgeBetweenMap[s1*6+s2];
} }
} }
@@ -0,0 +1,59 @@
package codechicken.multipart;
import net.minecraft.client.Minecraft;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.IBlockAccess;
import codechicken.lib.raytracer.ExtendedMOP;
import scala.Tuple2;
/**
* A helper class for resolving parts so we don't do a double look up
*/
public final class RenderPartResolver {
public static TMultiPart resolve(IBlockAccess world, int x, int y, int z) {
if (world == null) {
return null;
}
// Make sure the hit is actually this block.
MovingObjectPosition hit = Minecraft.getMinecraft().objectMouseOver;
if (hit == null || hit.blockX != x || hit.blockY != y || hit.blockZ != z) {
return null;
}
Object data = ExtendedMOP.getData(hit);
if (!(data instanceof Tuple2)) {
return null;
}
Tuple2<?, ?> hitInfo = (Tuple2<?, ?>) data;
Object indexObject = hitInfo._1();
if (!(indexObject instanceof Integer)) {
return null;
}
int index = (Integer) indexObject;
TileMultipartClient tile = getMultipartTile(world, x, y, z);
if (tile == null) {
return null;
}
// Needed because scala is stupid and the client tile doesn't expose what we need.
TileMultipart multipart = (TileMultipart) tile;
if (index < 0 || index >= multipart.jPartList().size()) {
return null;
}
return multipart.jPartList().get(index);
}
private static TileMultipartClient getMultipartTile(IBlockAccess world, int x, int y, int z) {
if (world.getTileEntity(x, y, z) instanceof TileMultipartClient) {
return (TileMultipartClient) world.getTileEntity(x, y, z);
}
return null;
}
}
@@ -10,30 +10,33 @@ import codechicken.lib.vec.Translation
import codechicken.lib.render.uv.IconTransformation import codechicken.lib.render.uv.IconTransformation
import cpw.mods.fml.relauncher.{Side, SideOnly} import cpw.mods.fml.relauncher.{Side, SideOnly}
/** /** Java class implementation
* Java class implementation */
*/
abstract class JCuboidPart extends TCuboidPart abstract class JCuboidPart extends TCuboidPart
/** /** Trait for parts that are simply a cuboid, having one bounding box. Overrides
* Trait for parts that are simply a cuboid, having one bounding box. Overrides multipart functions to this effect. * multipart functions to this effect.
*/ */
trait TCuboidPart extends TMultiPart trait TCuboidPart extends TMultiPart {
{
/**
* Return the bounding Cuboid6 for this part.
*/
def getBounds:Cuboid6
override def getSubParts:Iterable[IndexedCuboid6] = Seq(new IndexedCuboid6(0, getBounds)) /** Return the bounding Cuboid6 for this part.
*/
def getBounds: Cuboid6
override def getCollisionBoxes:Iterable[Cuboid6] = Seq(getBounds) override def getSubParts: Iterable[IndexedCuboid6] = Seq(
new IndexedCuboid6(0, getBounds)
)
@SideOnly(Side.CLIENT) override def getCollisionBoxes: Iterable[Cuboid6] = Seq(getBounds)
override def drawBreaking(renderBlocks:RenderBlocks)
{ @SideOnly(Side.CLIENT)
CCRenderState.reset() override def drawBreaking(renderBlocks: RenderBlocks) {
CCRenderState.setPipeline(new Translation(x, y, z), new IconTransformation(renderBlocks.overrideBlockTexture)) val state = CCRenderState.instance
BlockRenderer.renderCuboid(getBounds, 0) state.resetInstance()
} state.setPipelineInstance(
new Translation(x, y, z),
new IconTransformation(renderBlocks.overrideBlockTexture)
)
BlockRenderer.renderCuboid(getBounds, 0)
}
} }
@@ -1,12 +1,11 @@
package codechicken.multipart package codechicken.multipart
/** /** Interface which must be implemented by parts that go in an edge slot.
* Interface which must be implemented by parts that go in an edge slot. */
*/ trait TEdgePart extends TSlottedPart {
trait TEdgePart extends TSlottedPart
{ /** Return true if this part can conduct redstone signal or let redstone
/** * signal pass through it.
* Return true if this part can conduct redstone signal or let redstone signal pass through it. */
*/ def conductsRedstone = false
def conductsRedstone = false
} }
@@ -1,16 +1,17 @@
package codechicken.multipart package codechicken.multipart
/** /** Inteface which must be implemented by parts that go in a face part.
* Inteface which must be implemented by parts that go in a face part. */
*/ trait TFacePart extends TSlottedPart {
trait TFacePart extends TSlottedPart
{ /** Passed down from Block.isSideSolid. Return true if this part is solid and
/** * opaque on the specified side
* Passed down from Block.isSideSolid. Return true if this part is solid and opaque on the specified side */
*/ def solid(side: Int): Boolean = true
def solid(side:Int):Boolean = true
/** /** Return the redstone conduction map for which signal can pass through this
* Return the redstone conduction map for which signal can pass through this part on the face. Eg, hollow covers return 0x10 as signal can pass through the center hole. * part on the face. Eg, hollow covers return 0x10 as signal can pass through
*/ * the center hole.
def redstoneConductionMap = 0 */
def redstoneConductionMap = 0
} }
@@ -10,72 +10,83 @@ import codechicken.lib.vec.Vector3
import codechicken.lib.raytracer.ExtendedMOP import codechicken.lib.raytracer.ExtendedMOP
import codechicken.lib.render.EntityDigIconFX import codechicken.lib.render.EntityDigIconFX
/** /** This suite of 3 classes provides simple functions for standard minecraft
* This suite of 3 classes provides simple functions for standard minecraft style hit and break particles. * style hit and break particles.
* *
* Scala|Java composition setup. * Scala|Java composition setup. Due to the lack of mixin inheritance in Java,
* Due to the lack of mixin inheritance in Java, the classes are structured to suit both languages as follows. * the classes are structured to suit both languages as follows. IconHitEffects
* IconHitEffects contains static implementations of the functions that would be overriden in TMultiPart * contains static implementations of the functions that would be overriden in
* JIconHitEffects is the interface that should be implemented by a Java class, * TMultiPart JIconHitEffects is the interface that should be implemented by a
* which can then override the functions in TMultipart and call the static methods in IconHitEffects with 'this' as the first parameter * Java class, which can then override the functions in TMultipart and call the
* TIconHitEffects is a trait for scala implementors that does includes the overrides/static calls that Java programmers need to include themselves. * static methods in IconHitEffects with 'this' as the first parameter
*/ * TIconHitEffects is a trait for scala implementors that does includes the
object IconHitEffects * overrides/static calls that Java programmers need to include themselves.
{ */
def addHitEffects(part:JIconHitEffects, hit:MovingObjectPosition, effectRenderer:EffectRenderer) object IconHitEffects {
{ def addHitEffects(
EntityDigIconFX.addBlockHitEffects(part.tile.getWorldObj, part: JIconHitEffects,
part.getBounds.copy.add(Vector3.fromTileEntity(part.tile)), hit.sideHit, hit: MovingObjectPosition,
part.getBreakingIcon(ExtendedMOP.getData(hit), hit.sideHit), effectRenderer) effectRenderer: EffectRenderer
} ) {
EntityDigIconFX.addBlockHitEffects(
part.tile.getWorldObj,
part.getBounds.copy.add(Vector3.fromTileEntity(part.tile)),
hit.sideHit,
part.getBreakingIcon(ExtendedMOP.getData(hit), hit.sideHit),
effectRenderer
)
}
def addDestroyEffects(part:JIconHitEffects, effectRenderer:EffectRenderer) def addDestroyEffects(part: JIconHitEffects, effectRenderer: EffectRenderer) {
{ addDestroyEffects(part, effectRenderer, true)
addDestroyEffects(part, effectRenderer, true) }
}
def addDestroyEffects(part:JIconHitEffects, effectRenderer:EffectRenderer, scaleDensity:Boolean) def addDestroyEffects(
{ part: JIconHitEffects,
val icons = new Array[IIcon](6) effectRenderer: EffectRenderer,
for(i <- 0 until 6) scaleDensity: Boolean
icons(i) = part.getBrokenIcon(i) ) {
val bounds = val icons = new Array[IIcon](6)
if(scaleDensity) part.getBounds.copy for (i <- 0 until 6)
else Cuboid6.full.copy icons(i) = part.getBrokenIcon(i)
EntityDigIconFX.addBlockDestroyEffects(part.tile.getWorldObj, val bounds =
bounds.add(Vector3.fromTileEntity(part.tile)), icons, effectRenderer) if (scaleDensity) part.getBounds.copy
} else Cuboid6.full.copy
EntityDigIconFX.addBlockDestroyEffects(
part.tile.getWorldObj,
bounds.add(Vector3.fromTileEntity(part.tile)),
icons,
effectRenderer
)
}
} }
/** /** Java interface containing callbacks for particle rendering. Make sure to
* Java interface containing callbacks for particle rendering. * override addHitEffects and addDestroyEffects as in TIconHitEffects
* Make sure to override addHitEffects and addDestroyEffects as in TIconHitEffects */
*/ trait JIconHitEffects extends TMultiPart {
trait JIconHitEffects extends TMultiPart def getBounds: Cuboid6
{
def getBounds:Cuboid6
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
def getBreakingIcon(subPart:Any, side:Int):IIcon = getBrokenIcon(side) def getBreakingIcon(subPart: Any, side: Int): IIcon = getBrokenIcon(side)
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
def getBrokenIcon(side:Int):IIcon def getBrokenIcon(side: Int): IIcon
} }
/** /** Trait for scala programmers
* Trait for scala programmers */
*/ trait TIconHitEffects extends JIconHitEffects {
trait TIconHitEffects extends JIconHitEffects @SideOnly(Side.CLIENT)
{ override def addHitEffects(
@SideOnly(Side.CLIENT) hit: MovingObjectPosition,
override def addHitEffects(hit:MovingObjectPosition, effectRenderer:EffectRenderer) effectRenderer: EffectRenderer
{ ) {
IconHitEffects.addHitEffects(this, hit, effectRenderer) IconHitEffects.addHitEffects(this, hit, effectRenderer)
} }
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
override def addDestroyEffects(effectRenderer:EffectRenderer) override def addDestroyEffects(effectRenderer: EffectRenderer) {
{ IconHitEffects.addDestroyEffects(this, effectRenderer)
IconHitEffects.addDestroyEffects(this, effectRenderer) }
}
} }
@@ -23,282 +23,346 @@ import net.minecraft.util.Vec3
import codechicken.lib.raytracer.ExtendedMOP import codechicken.lib.raytracer.ExtendedMOP
import codechicken.lib.raytracer.RayTracer import codechicken.lib.raytracer.RayTracer
abstract class TMultiPart abstract class TMultiPart {
{
/**
* Reference to the container TileMultipart instance
*/
var tile:TileMultipart = _
/** /** Reference to the container TileMultipart instance
* Legacy helper function for getting the tile entity (from when TileMultipart was a trait). Use tile() now. */
*/ var tile: TileMultipart = _
@Deprecated
def getTile:TileEntity = tile
/**
* Getter for tile.worldObj
*/
def world = if(tile == null) null else tile.getWorldObj
/**
* Short getter for xCoord
*/
def x = tile.xCoord
/**
* Short getter for yCoord
*/
def y = tile.yCoord
/**
* Short getter for zCoord
*/
def z = tile.zCoord
/** /** Legacy helper function for getting the tile entity (from when
* The unique string identifier for this class of multipart. * TileMultipart was a trait). Use tile() now.
*/ */
def getType:String @Deprecated
/** def getTile: TileEntity = tile
* Called when the container tile instance is changed to update reference
*/
def bind(t:TileMultipart)
{
tile = t
}
/** /** Getter for tile.worldObj
* Perform an occlusion test to determine whether this and npart can 'fit' in this block space. */
*/ def world = if (tile == null) null else tile.getWorldObj
def occlusionTest(npart:TMultiPart):Boolean = true
/**
* Return a list of entity collision boxes.
* Note all Cuboid6's returned by methods in TMultiPart should be within (0,0,0)->(1,1,1)
*/
def getCollisionBoxes:Iterable[Cuboid6] = Seq()
/**
* Perform a raytrace of this part. The default implementation does a Cuboid6 ray trace on bounding boxes returned from getSubParts.
* This should only be overridden if you need special ray-tracing capabilities such as triangular faces.
* The returned ExtendedMOP will be passed to methods such as 'activate' so it is recommended to use the data field to indicate information about the hit area.
*/
def collisionRayTrace(start: Vec3, end: Vec3): ExtendedMOP = {
val offset = new Vector3(x, y, z)
val boxes = getSubParts.map(c => new IndexedCuboid6(c.data, c.copy.add(offset)))
return RayTracer.instance.rayTraceCuboids(new Vector3(start), new Vector3(end), boxes.toList,
new BlockCoord(x, y, z), tile.getBlockType).asInstanceOf[ExtendedMOP]
}
/**
* For the default collisionRayTrace implementation, returns a list of indexed bounding boxes. The data field of ExtendedMOP will be set to the index of the cuboid the raytrace hit.
*/
def getSubParts:Iterable[IndexedCuboid6] = Seq()
/** /** Short getter for xCoord
* Return a list of items that should be dropped when this part is destroyed. */
*/ def x = tile.xCoord
def getDrops:Iterable[ItemStack] = Seq()
/**
* Return a value indicating how hard this part is to break
* @param hit An instance of ExtendedMOP from collisionRayTrace
*/
def getStrength(hit:MovingObjectPosition, player:EntityPlayer):Float = 1
/**
* Harvest this part, removing it from the container tile and dropping items if necessary.
* @param hit An instance of ExtendedMOP from collisionRayTrace
* @param player The player harvesting the part
*/
def harvest(hit:MovingObjectPosition, player:EntityPlayer)
{
if(!player.capabilities.isCreativeMode)
tile.dropItems(getDrops)
tile.remPart(this)
}
/**
* The light level emitted by this part
*/
def getLightValue = 0
/** /** Short getter for yCoord
* If any part returns true for this, torches can be placed. Vanilla hacks... */
*/ def y = tile.yCoord
def canPlaceTorchOnTop = false
/** /** Short getter for zCoord
* Explosion resistance of the host tile is the maximum explosion resistance of the contained parts */
* @param entity The entity responsible for this explosion def z = tile.zCoord
* @return The resistance of this part the the explosion
*/
def explosionResistance(entity:Entity) = 0F
/** /** The unique string identifier for this class of multipart.
* Add particles and other effects when a player is mining this part */
* @param hit An instance of ExtendedMOP from collisionRayTrace def getType: String
*/
@SideOnly(Side.CLIENT)
def addHitEffects(hit:MovingObjectPosition, effectRenderer:EffectRenderer){}
/**
* Add particles and other effects when a player broke this part
* @param hit An instance of ExtendedMOP from collisionRayTrace
*/
@SideOnly(Side.CLIENT)
def addDestroyEffects(hit:MovingObjectPosition, effectRenderer:EffectRenderer) {addDestroyEffects(effectRenderer)}
@SideOnly(Side.CLIENT) /** Called when the container tile instance is changed to update reference
@Deprecated */
def addDestroyEffects(effectRenderer:EffectRenderer){} def bind(t: TileMultipart) {
/** tile = t
* Render the static, unmoving faces of this part into the world renderer. }
* The Tessellator is already drawing.
* @param pass The render pass, 1 or 0
* @return true if vertices were added to the tessellator
*/
@SideOnly(Side.CLIENT)
def renderStatic(pos:Vector3, pass:Int) = false
/**
* Render the dynamic, changing faces of this part and other gfx as in a TESR.
* The Tessellator will need to be started if it is to be used.
* @param pos The position of this block space relative to the renderer, same as x, y, z passed to TESR.
* @param frame The partial interpolation frame value for animations between ticks
* @param pass The render pass, 1 or 0
*/
@SideOnly(Side.CLIENT)
def renderDynamic(pos:Vector3, frame:Float, pass:Int){}
/**
* Draw the breaking overlay for this part. The overrideIcon in RenderBlocks will be set to the fracture icon.
*/
@SideOnly(Side.CLIENT)
def drawBreaking(renderBlocks:RenderBlocks){}
/**
* Override the drawing of the selection box around this part.
* @param hit An instance of ExtendedMOP from collisionRayTrace
* @return true if highlight rendering was overridden.
*/
@SideOnly(Side.CLIENT)
def drawHighlight(hit:MovingObjectPosition, player:EntityPlayer, frame:Float):Boolean = false
/**
* @return A Cuboid6 bounding the render of this part for frustum culling. The bounds are relative to the tile coordinates.
*/
def getRenderBounds = Cuboid6.full
/** /** Perform an occlusion test to determine whether this and npart can 'fit' in
* Write all the data required to describe a client version of this part to the packet. * this block space.
* Called serverside, when a client loads this part for the first time. */
*/ def occlusionTest(npart: TMultiPart): Boolean = true
def writeDesc(packet:MCDataOutput){}
/**
* Fill out this part with the description information contained in packet. Will be exactly as written from writeDesc.
* Called clientside when a client loads this part for the first time.
*/
def readDesc(packet:MCDataInput){}
/**
* Save part to NBT (only called serverside)
*/
def save(tag:NBTTagCompound){}
/**
* Load part from NBT (only called serverside)
*/
def load(tag:NBTTagCompound){}
/**
* Gets a MCDataOutput instance for writing update data to clients with this part loaded.
* The write stream functions as a buffer which is flushed in a compressed databurst packet at the end of the tick.
*/
def getWriteStream:MCDataOutput = tile.getWriteStream(this)
/**
* Read and operate on data written to getWriteStream. Ensure all data this part wrote is read even if it's not going to be used.
* The default implementation assumes a call to sendDescUpdate as the only use of getWriteStream.
*/
def read(packet:MCDataInput)
{
readDesc(packet)
tile.markRender()
}
/**
* Quick and easy method to re-describe the whole part on the client. This will call read on the client which calls readDesc unless overriden.
* Incremental changes should be sent rather than the whole description packet if possible.
*/
def sendDescUpdate() = writeDesc(getWriteStream)
/** /** Return a list of entity collision boxes. Note all Cuboid6's returned by
* Called when a part is added or removed from this block space. * methods in TMultiPart should be within (0,0,0)->(1,1,1)
* The part parameter may be null if several things have changed. */
*/ def getCollisionBoxes: Iterable[Cuboid6] = Seq()
def onPartChanged(part:TMultiPart){}
/**
* Called when a neighbor block changed
*/
def onNeighborChanged(){}
/**
* Called when this part is added to the block space
*/
def onAdded() = onWorldJoin()
/**
* Called when this part is removed from the block space
*/
def onRemoved() = onWorldSeparate()
/**
* Called when the containing chunk is loaded on the server.
*/
def onChunkLoad() = onWorldJoin()
/**
* Called when the containing chunk is unloaded on the server.
*/
def onChunkUnload() = onWorldSeparate()
/**
* Called when this part separates from the world (due to removal, chunk unload or other). Use this to sync with external data structures. Called on both client and server
*/
def onWorldSeparate(){}
/**
* Called when this part joins the world (due to placement, chunkload or frame move etc). Use this to sync with external data structures. Called on both client and server
*/
def onWorldJoin(){}
/**
* Called when this part is converted from a normal block/tile (only applicable if a converter has been registered)
*/
def onConverted() = onAdded()
/**
* Called when this part is converted from a normal block/tile (only applicable if a converter has been registered) before the original tile has been replaced
* Use this to clear out things like inventory from the old tile.
*/
def invalidateConvertedTile(){}
/**
* Called when this part has been moved without a save/load.
*/
def onMoved() = onWorldJoin()
/**
* Called just before this part is actually removed from the container tile
*/
def preRemove(){}
/** /** Perform a raytrace of this part. The default implementation does a Cuboid6
* Return whether this part needs update ticks. This will only be called on addition/removal so it should be a constant for this instance. * ray trace on bounding boxes returned from getSubParts. This should only be
*/ * overridden if you need special ray-tracing capabilities such as triangular
def doesTick = true * faces. The returned ExtendedMOP will be passed to methods such as
/** * 'activate' so it is recommended to use the data field to indicate
* Called once per world tick. This will be called even if doesTick returns false if another part in the space needs ticks. * information about the hit area.
*/ */
def update(){} def collisionRayTrace(start: Vec3, end: Vec3): ExtendedMOP = {
/** val offset = new Vector3(x, y, z)
* Called when a scheduled tick is executed. val boxes =
*/ getSubParts.map(c => new IndexedCuboid6(c.data, c.copy.add(offset)))
def scheduledTick(){} return RayTracer.instance
/** .rayTraceCuboids(
* Sets a scheduledTick callback for this part ticks in the future. This is a world time value, so if the chunk is unloaded and reloaded some time later, the tick may fire immediately. new Vector3(start),
*/ new Vector3(end),
def scheduleTick(ticks:Int) = TickScheduler.scheduleTick(this, ticks) boxes.toList,
new BlockCoord(x, y, z),
tile.getBlockType
)
.asInstanceOf[ExtendedMOP]
}
/** /** For the default collisionRayTrace implementation, returns a list of
* Return the itemstack for the middle click pick-block function. * indexed bounding boxes. The data field of ExtendedMOP will be set to the
*/ * index of the cuboid the raytrace hit.
def pickItem(hit:MovingObjectPosition):ItemStack = null */
/** def getSubParts: Iterable[IndexedCuboid6] = Seq()
* Called on block right click. item is the player's held item.
* This should not modify the part client side. If the client call returns false, the server will not call this function. /** Return a list of items that should be dropped when this part is destroyed.
* @param hit An instance of ExtendedMOP from collisionRayTrace */
*/ def getDrops: Iterable[ItemStack] = Seq()
def activate(player:EntityPlayer, hit:MovingObjectPosition, item:ItemStack) = false
/** /** Return a value indicating how hard this part is to break
* Called on block left click. item is the player's held item. * @param hit
* @param hit An instance of ExtendedMOP from collisionRayTrace * An instance of ExtendedMOP from collisionRayTrace
*/ */
def click(player:EntityPlayer, hit:MovingObjectPosition, item:ItemStack){} def getStrength(hit: MovingObjectPosition, player: EntityPlayer): Float = 1
/**
* Called when an entity is within this block space. May not actually collide with this part. /** Harvest this part, removing it from the container tile and dropping items
*/ * if necessary.
def onEntityCollision(entity:Entity){} * @param hit
* An instance of ExtendedMOP from collisionRayTrace
* @param player
* The player harvesting the part
*/
def harvest(hit: MovingObjectPosition, player: EntityPlayer) {
if (!player.capabilities.isCreativeMode)
tile.dropItems(getDrops)
tile.remPart(this)
}
/** The light level emitted by this part
*/
def getLightValue = 0
/** If any part returns true for this, torches can be placed. Vanilla hacks...
*/
def canPlaceTorchOnTop = false
/** Explosion resistance of the host tile is the maximum explosion resistance
* of the contained parts
* @param entity
* The entity responsible for this explosion
* @return
* The resistance of this part the the explosion
*/
def explosionResistance(entity: Entity) = 0f
/** Add particles and other effects when a player is mining this part
* @param hit
* An instance of ExtendedMOP from collisionRayTrace
*/
@SideOnly(Side.CLIENT)
def addHitEffects(
hit: MovingObjectPosition,
effectRenderer: EffectRenderer
) {}
/** Add particles and other effects when a player broke this part
* @param hit
* An instance of ExtendedMOP from collisionRayTrace
*/
@SideOnly(Side.CLIENT)
def addDestroyEffects(
hit: MovingObjectPosition,
effectRenderer: EffectRenderer
) { addDestroyEffects(effectRenderer) }
@SideOnly(Side.CLIENT)
@Deprecated
def addDestroyEffects(effectRenderer: EffectRenderer) {}
/** Render the static, unmoving faces of this part into the world renderer.
* The Tessellator is already drawing.
* @param pass
* The render pass, 1 or 0
* @return
* true if vertices were added to the tessellator
*/
@SideOnly(Side.CLIENT)
def renderStatic(pos: Vector3, pass: Int) = false
/** Render the dynamic, changing faces of this part and other gfx as in a
* TESR. The Tessellator will need to be started if it is to be used.
* @param pos
* The position of this block space relative to the renderer, same as x, y,
* z passed to TESR.
* @param frame
* The partial interpolation frame value for animations between ticks
* @param pass
* The render pass, 1 or 0
*/
@SideOnly(Side.CLIENT)
def renderDynamic(pos: Vector3, frame: Float, pass: Int) {}
/** Draw the breaking overlay for this part. The overrideIcon in RenderBlocks
* will be set to the fracture icon.
*/
@SideOnly(Side.CLIENT)
def drawBreaking(renderBlocks: RenderBlocks) {}
/** Override the drawing of the selection box around this part.
* @param hit
* An instance of ExtendedMOP from collisionRayTrace
* @return
* true if highlight rendering was overridden.
*/
@SideOnly(Side.CLIENT)
def drawHighlight(
hit: MovingObjectPosition,
player: EntityPlayer,
frame: Float
): Boolean = false
/** @return
* A Cuboid6 bounding the render of this part for frustum culling. The
* bounds are relative to the tile coordinates.
*/
def getRenderBounds = Cuboid6.full
/** Write all the data required to describe a client version of this part to
* the packet. Called serverside, when a client loads this part for the first
* time.
*/
def writeDesc(packet: MCDataOutput) {}
/** Fill out this part with the description information contained in packet.
* Will be exactly as written from writeDesc. Called clientside when a client
* loads this part for the first time.
*/
def readDesc(packet: MCDataInput) {}
/** Save part to NBT (only called serverside)
*/
def save(tag: NBTTagCompound) {}
/** Load part from NBT (only called serverside)
*/
def load(tag: NBTTagCompound) {}
/** Gets a MCDataOutput instance for writing update data to clients with this
* part loaded. The write stream functions as a buffer which is flushed in a
* compressed databurst packet at the end of the tick.
*/
def getWriteStream: MCDataOutput = tile.getWriteStream(this)
/** Read and operate on data written to getWriteStream. Ensure all data this
* part wrote is read even if it's not going to be used. The default
* implementation assumes a call to sendDescUpdate as the only use of
* getWriteStream.
*/
def read(packet: MCDataInput) {
readDesc(packet)
tile.markRender()
}
/** Quick and easy method to re-describe the whole part on the client. This
* will call read on the client which calls readDesc unless overriden.
* Incremental changes should be sent rather than the whole description
* packet if possible.
*/
def sendDescUpdate() {
if (tile != null) writeDesc(getWriteStream)
}
/** Called when a part is added or removed from this block space. The part
* parameter may be null if several things have changed.
*/
def onPartChanged(part: TMultiPart) {}
/** Called when a neighbor block changed
*/
def onNeighborChanged() {}
/** Called when this part is added to the block space
*/
def onAdded() = onWorldJoin()
/** Called when this part is removed from the block space
*/
def onRemoved() = onWorldSeparate()
/** Called when the containing chunk is loaded on the server.
*/
def onChunkLoad() = onWorldJoin()
/** Called when the containing chunk is unloaded on the server.
*/
def onChunkUnload() = onWorldSeparate()
/** Called when this part separates from the world (due to removal, chunk
* unload or other). Use this to sync with external data structures. Called
* on both client and server
*/
def onWorldSeparate() {}
/** Called when this part joins the world (due to placement, chunkload or
* frame move etc). Use this to sync with external data structures. Called on
* both client and server
*/
def onWorldJoin() {}
/** Called when this part is converted from a normal block/tile (only
* applicable if a converter has been registered)
*/
def onConverted() = onAdded()
/** Called when this part is converted from a normal block/tile (only
* applicable if a converter has been registered) before the original tile
* has been replaced Use this to clear out things like inventory from the old
* tile.
*/
def invalidateConvertedTile() {}
/** Called when this part has been moved without a save/load.
*/
def onMoved() = onWorldJoin()
/** Called just before this part is actually removed from the container tile
*/
def preRemove() {}
/** Return whether this part needs update ticks. This will only be called on
* addition/removal so it should be a constant for this instance.
*/
def doesTick = true
/** Return whether this part needs to be included in the dynamic render loop
* (renderDynamic). Default is false. Override this to true for parts like
* lights that need per-frame rendering but no logic updates.
*/
def shouldRenderDynamic = false
/** Called once per world tick. This will be called even if doesTick returns
* false if another part in the space needs ticks.
*/
def update() {}
/** Called when a scheduled tick is executed.
*/
def scheduledTick() {}
/** Sets a scheduledTick callback for this part ticks in the future. This is a
* world time value, so if the chunk is unloaded and reloaded some time
* later, the tick may fire immediately.
*/
def scheduleTick(ticks: Int) = TickScheduler.scheduleTick(this, ticks)
/** Return the itemstack for the middle click pick-block function.
*/
def pickItem(hit: MovingObjectPosition): ItemStack = null
/** Called on block right click. item is the player's held item. This should
* not modify the part client side. If the client call returns false, the
* server will not call this function.
* @param hit
* An instance of ExtendedMOP from collisionRayTrace
*/
def activate(
player: EntityPlayer,
hit: MovingObjectPosition,
item: ItemStack
) = false
/** Called on block left click. item is the player's held item.
* @param hit
* An instance of ExtendedMOP from collisionRayTrace
*/
def click(player: EntityPlayer, hit: MovingObjectPosition, item: ItemStack) {}
/** Called when an entity is within this block space. May not actually collide
* with this part.
*/
def onEntityCollision(entity: Entity) {}
} }
@@ -4,65 +4,62 @@ import codechicken.lib.vec.Cuboid6
import scala.collection.JavaConversions._ import scala.collection.JavaConversions._
import java.lang.Iterable import java.lang.Iterable
/** /** This suite of 3 classes provides simple functions for standard bounding box
* This suite of 3 classes provides simple functions for standard bounding box based occlusion testing. * based occlusion testing. If any two parts have overlapping bounding boxes,
* If any two parts have overlapping bounding boxes, the test fails * the test fails
* *
* See TIconHitEffects for notes on the Scala|Java composition setup. * See TIconHitEffects for notes on the Scala|Java composition setup.
*/ */
object NormalOcclusionTest object NormalOcclusionTest {
{
/**
* Performs the test, returns true if the test fails
*/
def apply(boxes1:Traversable[Cuboid6], boxes2:Traversable[Cuboid6]):Boolean =
boxes1.forall(v1 => boxes2.forall(v2 => !v1.intersects(v2)))
/** /** Performs the test, returns true if the test fails
* Performs the test, returns true if the test fails */
*/ def apply(
def apply(part1:JNormalOcclusion, part2:TMultiPart):Boolean = boxes1: Traversable[Cuboid6],
{ boxes2: Traversable[Cuboid6]
var boxes = Seq[Cuboid6]() ): Boolean =
if(part2.isInstanceOf[JNormalOcclusion]) boxes1.forall(v1 => boxes2.forall(v2 => !v1.intersects(v2)))
boxes = boxes++part2.asInstanceOf[JNormalOcclusion].getOcclusionBoxes
if(part2.isInstanceOf[JPartialOcclusion]) /** Performs the test, returns true if the test fails
boxes = boxes++part2.asInstanceOf[JPartialOcclusion].getPartialOcclusionBoxes */
def apply(part1: JNormalOcclusion, part2: TMultiPart): Boolean = {
var boxes = Seq[Cuboid6]()
if (part2.isInstanceOf[JNormalOcclusion])
boxes = boxes ++ part2.asInstanceOf[JNormalOcclusion].getOcclusionBoxes
return NormalOcclusionTest(boxes, part1.getOcclusionBoxes) if (part2.isInstanceOf[JPartialOcclusion])
} boxes =
boxes ++ part2.asInstanceOf[JPartialOcclusion].getPartialOcclusionBoxes
return NormalOcclusionTest(boxes, part1.getOcclusionBoxes)
}
} }
/** /** Java interface containing callbacks for normal occlusion testing. Make sure
* Java interface containing callbacks for normal occlusion testing. * to override occlusionTest as in TNormalOcclusion
* Make sure to override occlusionTest as in TNormalOcclusion */
*/ trait JNormalOcclusion {
trait JNormalOcclusion
{ /** Return a list of normal occlusion boxes
/** */
* Return a list of normal occlusion boxes def getOcclusionBoxes: Iterable[Cuboid6]
*/
def getOcclusionBoxes:Iterable[Cuboid6]
} }
/** /** Trait for scala programmers
* Trait for scala programmers */
*/ trait TNormalOcclusion extends TMultiPart with JNormalOcclusion {
trait TNormalOcclusion extends TMultiPart with JNormalOcclusion override def occlusionTest(npart: TMultiPart): Boolean =
{ NormalOcclusionTest(this, npart) && super.occlusionTest(npart)
override def occlusionTest(npart:TMultiPart):Boolean =
NormalOcclusionTest(this, npart) && super.occlusionTest(npart)
} }
/** /** Utility part class for performing 3rd party occlusion tests
* Utility part class for performing 3rd party occlusion tests */
*/ class NormallyOccludedPart(bounds: Iterable[Cuboid6])
class NormallyOccludedPart(bounds:Iterable[Cuboid6]) extends TMultiPart with TNormalOcclusion extends TMultiPart
{ with TNormalOcclusion {
def this(bound:Cuboid6) = this(Seq(bound)) def this(bound: Cuboid6) = this(Seq(bound))
def getType = null def getType = null
def getOcclusionBoxes = bounds def getOcclusionBoxes = bounds
} }
@@ -4,73 +4,70 @@ import codechicken.lib.vec.Cuboid6
import scala.collection.JavaConversions._ import scala.collection.JavaConversions._
import java.lang.Iterable import java.lang.Iterable
/** /** This class provides a special type of occlusion model used by microblocks.
* This class provides a special type of occlusion model used by microblocks. * The partial occlusion test defines bounding boxes that may intersect, so
* The partial occlusion test defines bounding boxes that may intersect, so long as no part is completely obscured by a combination of the others. * long as no part is completely obscured by a combination of the others.
* Partial bounding boxes may not intersect with normal bounding boxes from NormalOcclusionTest * Partial bounding boxes may not intersect with normal bounding boxes from
* * NormalOcclusionTest
* This test is actually managed by the mixin trait TPartialOcclusionTile which is generated when the marker interface JPartialOcclusion is found *
*/ * This test is actually managed by the mixin trait TPartialOcclusionTile which
class PartialOcclusionTest(size:Int) * is generated when the marker interface JPartialOcclusion is found
{ */
/** class PartialOcclusionTest(size: Int) {
* The resolution of the test, set to 1/8th of a block
*/
val res = 8
val bits = new Array[Byte](res*res*res)
val partial = new Array[Boolean](size)
def fill(i:Int, part:JPartialOcclusion) /** The resolution of the test, set to 1/8th of a block
{ */
fill(i, part.getPartialOcclusionBoxes, part.allowCompleteOcclusion) val res = 8
} val bits = new Array[Byte](res * res * res)
val partial = new Array[Boolean](size)
def fill(i:Int, boxes:Iterable[Cuboid6], complete:Boolean) def fill(i: Int, part: JPartialOcclusion) {
{ fill(i, part.getPartialOcclusionBoxes, part.allowCompleteOcclusion)
partial(i) = !complete }
boxes.foreach(box => fill(i+1, box))
}
def fill(v:Int, box:Cuboid6) def fill(i: Int, boxes: Iterable[Cuboid6], complete: Boolean) {
{ partial(i) = !complete
for(x <- (box.min.x*res+0.5).toInt until (box.max.x*res+0.5).toInt) boxes.foreach(box => fill(i + 1, box))
for(y <- (box.min.y*res+0.5).toInt until (box.max.y*res+0.5).toInt) }
for(z <- (box.min.z*res+0.5).toInt until (box.max.z*res+0.5).toInt)
{
val i = (x*res+y)*res+z
if(bits(i) == 0)
bits(i) = v.toByte
else
bits(i) = -1
}
}
def apply():Boolean = def fill(v: Int, box: Cuboid6) {
{ for (x <- (box.min.x * res + 0.5).toInt until (box.max.x * res + 0.5).toInt)
val visible = new Array[Boolean](size) for (
bits.foreach(n => if(n > 0) visible(n-1) = true) y <- (box.min.y * res + 0.5).toInt until (box.max.y * res + 0.5).toInt
)
var i = 0 for (
while(i < partial.length) z <- (box.min.z * res + 0.5).toInt until (box.max.z * res + 0.5).toInt
{ ) {
if(partial(i) && !visible(i)) val i = (x * res + y) * res + z
return false if (bits(i) == 0)
i+=1 bits(i) = v.toByte
else
bits(i) = -1
} }
}
return true def apply(): Boolean = {
val visible = new Array[Boolean](size)
bits.foreach(n => if (n > 0) visible(n - 1) = true)
var i = 0
while (i < partial.length) {
if (partial(i) && !visible(i))
return false
i += 1
} }
return true
}
} }
trait JPartialOcclusion trait JPartialOcclusion {
{
/**
* Return a list of partial occlusion boxes
*/
def getPartialOcclusionBoxes:Iterable[Cuboid6]
/** /** Return a list of partial occlusion boxes
* Return true if this part may be completely obscured */
*/ def getPartialOcclusionBoxes: Iterable[Cuboid6]
def allowCompleteOcclusion = false
/** Return true if this part may be completely obscured
*/
def allowCompleteOcclusion = false
} }
@@ -1,19 +1,19 @@
package codechicken.multipart package codechicken.multipart
/** /** Interface for parts with random update ticks. Used in conjuction with
* Interface for parts with random update ticks. Used in conjuction with TickScheduler * TickScheduler
*/ */
trait TRandomUpdateTick extends TMultiPart trait TRandomUpdateTick extends TMultiPart {
{
/**
* Called on random update. Random ticks are between 800 and 1600 ticks from their last scheduled/random tick
*/
def randomUpdate()
/** /** Called on random update. Random ticks are between 800 and 1600 ticks from
* If implementing interface in java, be sure to implement this method yourself * their last scheduled/random tick
*/ */
override def onWorldJoin() { def randomUpdate()
TickScheduler.loadRandomTick(this)
} /** If implementing interface in java, be sure to implement this method
* yourself
*/
override def onWorldJoin() {
TickScheduler.loadRandomTick(this)
}
} }
@@ -1,15 +1,14 @@
package codechicken.multipart package codechicken.multipart
/** /** Interface for parts that fill a slot based configuration as defined in
* Interface for parts that fill a slot based configuration as defined in PartMap. * PartMap. If this is implemented, calling partMap(slot) on the host tile will
* If this is implemented, calling partMap(slot) on the host tile will return this part if the corresponding bit in the slotMask is set * return this part if the corresponding bit in the slotMask is set
* *
* Marker interface for TSlottedTile * Marker interface for TSlottedTile
*/ */
trait TSlottedPart extends TMultiPart trait TSlottedPart extends TMultiPart {
{
/** /** a bitmask of slots that this part fills. slot x is 1<<x
* a bitmask of slots that this part fills. slot x is 1<<x */
*/ def getSlotMask: Int
def getSlotMask:Int
} }
@@ -18,243 +18,242 @@ import java.io.FileOutputStream
import java.io.FileInputStream import java.io.FileInputStream
import net.minecraft.world.storage.SaveHandler import net.minecraft.world.storage.SaveHandler
/** /** Used for scheduling delayed callbacks to parts. Do not use this for redstone
* Used for scheduling delayed callbacks to parts. * applications that require precise timing. If 2 parts are both scheduled for
* Do not use this for redstone applications that require precise timing. * an update on the same tick, there is no guarantee which one will update
* If 2 parts are both scheduled for an update on the same tick, there is no guarantee which one will update first. * first. These parts should not depend on a state of another part that may
* These parts should not depend on a state of another part that may have changed before/after them. * have changed before/after them.
*/ */
object TickScheduler extends WorldExtensionInstantiator object TickScheduler extends WorldExtensionInstantiator {
{ class PartTickEntry(
class PartTickEntry(val part:TMultiPart, var time:Long, var random:Boolean) val part: TMultiPart,
{ var time: Long,
def this(part:TMultiPart, ticks:Int) = this(part, ticks, false) var random: Boolean
) {
def this(part: TMultiPart, ticks: Int) = this(part, ticks, false)
}
private class WorldTickScheduler(world$ : World)
extends WorldExtension(world$) {
var schedTime = 0L
var tickChunks = HashSet[ChunkTickScheduler]()
private var processing = false
private val pending = ListBuffer[PartTickEntry]()
def scheduleTick(part: TMultiPart, ticks: Int, random: Boolean) {
if (processing)
pending += new PartTickEntry(part, schedTime + ticks, random)
else
_scheduleTick(part, schedTime + ticks, random)
} }
private class WorldTickScheduler(world$:World) extends WorldExtension(world$) def _scheduleTick(part: TMultiPart, time: Long, random: Boolean) {
{ if (part.tile != null)
var schedTime = 0L getChunkExtension(part.tile.xCoord >> 4, part.tile.zCoord >> 4)
var tickChunks = HashSet[ChunkTickScheduler]() .asInstanceOf[ChunkTickScheduler]
private var processing = false .scheduleTick(part, time, random)
private val pending = ListBuffer[PartTickEntry]()
def scheduleTick(part:TMultiPart, ticks:Int, random:Boolean)
{
if(processing)
pending+=new PartTickEntry(part, schedTime+ticks, random)
else
_scheduleTick(part, schedTime+ticks, random)
}
def _scheduleTick(part:TMultiPart, time:Long, random:Boolean)
{
if(part.tile != null)
getChunkExtension(part.tile.xCoord>>4, part.tile.zCoord>>4)
.asInstanceOf[ChunkTickScheduler].scheduleTick(part, time, random)
}
def loadRandom(part:TRandomUpdateTick) = scheduleTick(part, nextRandomTick, true)
override def preTick()
{
processing = true
}
override def postTick()
{
if(!tickChunks.isEmpty)
tickChunks = tickChunks.filter(_.processTicks())
processing = false
pending.foreach(e => _scheduleTick(e.part, e.time, e.random))
pending.clear()
schedTime+=1
}
def saveDir:File =
{
if(world.provider.dimensionId == 0)//Calling DimensionManager.getCurrentSaveRootDirectory too early breaks game saves, we have a world reference, use it
return world.getSaveHandler.asInstanceOf[SaveHandler].getWorldDirectory
return new File(DimensionManager.getCurrentSaveRootDirectory, world.provider.getSaveFolder)
}
def saveFile:File = new File(saveDir, "multipart.dat")
override def load()
{
try
{
val in = new FileInputStream(saveFile)
loadTag(CompressedStreamTools.readCompressed(in))
in.close()
}
catch
{
case e:Exception =>
}
loadTag(new NBTTagCompound)
}
def loadTag(tag:NBTTagCompound)
{
if(tag.hasKey("schedTime"))
schedTime = tag.getLong("schedTime")
else
schedTime = world.getTotalWorldTime
}
def saveTag:NBTTagCompound =
{
val tag = new NBTTagCompound
tag.setLong("schedTime", schedTime)
return tag
}
override def save() {
val file = saveFile
if(!file.getParentFile.exists)
file.getParentFile.mkdirs()
if(!file.exists)
file.createNewFile()
val dout = new DataOutputStream(new FileOutputStream(file))
CompressedStreamTools.writeCompressed(saveTag, dout)
dout.close()
}
def nextRandomTick = world.rand.nextInt(800)+800
} }
def createWorldExtension(world:World):WorldExtension = new WorldTickScheduler(world) def loadRandom(part: TRandomUpdateTick) =
scheduleTick(part, nextRandomTick, true)
private class ChunkTickScheduler(chunk$:Chunk, world:WorldTickScheduler) extends ChunkExtension(chunk$, world) override def preTick() {
{ processing = true
import codechicken.multipart.handler.MultipartProxy._ }
var tickList = ListBuffer[PartTickEntry]() override def postTick() {
if (!tickChunks.isEmpty)
tickChunks = tickChunks.filter(_.processTicks())
def schedTime = world.schedTime processing = false
pending.foreach(e => _scheduleTick(e.part, e.time, e.random))
pending.clear()
def scheduleTick(part:TMultiPart, time:Long, random:Boolean) schedTime += 1
{ }
val it = tickList.iterator
while(it.hasNext) def saveDir: File = {
if (
world.provider.dimensionId == 0
) // Calling DimensionManager.getCurrentSaveRootDirectory too early breaks game saves, we have a world reference, use it
return world.getSaveHandler.asInstanceOf[SaveHandler].getWorldDirectory
return new File(
DimensionManager.getCurrentSaveRootDirectory,
world.provider.getSaveFolder
)
}
def saveFile: File = new File(saveDir, "multipart.dat")
override def load() {
try {
val in = new FileInputStream(saveFile)
loadTag(CompressedStreamTools.readCompressed(in))
in.close()
} catch {
case e: Exception =>
}
loadTag(new NBTTagCompound)
}
def loadTag(tag: NBTTagCompound) {
if (tag.hasKey("schedTime"))
schedTime = tag.getLong("schedTime")
else
schedTime = world.getTotalWorldTime
}
def saveTag: NBTTagCompound = {
val tag = new NBTTagCompound
tag.setLong("schedTime", schedTime)
return tag
}
override def save() {
val file = saveFile
if (!file.getParentFile.exists)
file.getParentFile.mkdirs()
if (!file.exists)
file.createNewFile()
val dout = new DataOutputStream(new FileOutputStream(file))
CompressedStreamTools.writeCompressed(saveTag, dout)
dout.close()
}
def nextRandomTick = world.rand.nextInt(800) + 800
}
def createWorldExtension(world: World): WorldExtension =
new WorldTickScheduler(world)
private class ChunkTickScheduler(chunk$ : Chunk, world: WorldTickScheduler)
extends ChunkExtension(chunk$, world) {
import codechicken.multipart.handler.MultipartProxy._
var tickList = ListBuffer[PartTickEntry]()
def schedTime = world.schedTime
def scheduleTick(part: TMultiPart, time: Long, random: Boolean) {
val it = tickList.iterator
while (it.hasNext) {
val e = it.next()
if (e.part == part) {
if (
e.random && !random
) // only override an existing tick if we're going from random->scheduled
{ {
val e = it.next() e.time = time
if(e.part == part) e.random = random
{
if(e.random && !random)//only override an existing tick if we're going from random->scheduled
{
e.time = time
e.random = random
}
return
}
} }
tickList+=new PartTickEntry(part, time, random) return
if(tickList.size == 1)
world.tickChunks+=this
} }
}
tickList += new PartTickEntry(part, time, random)
if (tickList.size == 1)
world.tickChunks += this
}
def nextRandomTick = world.nextRandomTick def nextRandomTick = world.nextRandomTick
def processTicks():Boolean = def processTicks(): Boolean = {
{ tickList = tickList.filter(processTick)
tickList = tickList.filter(processTick) return !tickList.isEmpty
return !tickList.isEmpty }
}
def processTick(e:PartTickEntry):Boolean = def processTick(e: PartTickEntry): Boolean = {
{ if (e.time <= schedTime) {
if(e.time <= schedTime) if (e.part.tile != null) {
{ if (e.random && e.part.isInstanceOf[TRandomUpdateTick])
if(e.part.tile != null) e.part.asInstanceOf[TRandomUpdateTick].randomUpdate()
{ else
if(e.random && e.part.isInstanceOf[TRandomUpdateTick]) e.part.scheduledTick()
e.part.asInstanceOf[TRandomUpdateTick].randomUpdate()
else
e.part.scheduledTick()
if(e.part.isInstanceOf[TRandomUpdateTick]) if (e.part.isInstanceOf[TRandomUpdateTick]) {
{ e.time = schedTime + nextRandomTick
e.time = schedTime+nextRandomTick e.random = true
e.random = true
return true
}
}
return false
}
return true return true
}
} }
return false
override def saveData(data:NBTTagCompound) }
{ return true
val tagList = new NBTTagList
tickList.foreach{e =>
val part = e.part
if(part.tile != null && !e.random)
{
val tag = new NBTTagCompound
tag.setShort("pos", indexInChunk(new BlockCoord(part.tile)).toShort)
tag.setByte("i", part.tile.partList.indexOf(part).toByte)
tag.setLong("time", e.time)
tagList.appendTag(tag)
}
}
if(tagList.tagCount > 0)
data.setTag("multipartTicks", tagList)
}
override def loadData(data:NBTTagCompound)
{
tickList.clear()
if(!data.hasKey("multipartTicks"))
return
val tagList = data.getTagList("multipartTicks", 10)
val cc = new ChunkCoordIntPair(0, 0)
for(i <- 0 until tagList.tagCount)
{
val tag = tagList.getCompoundTagAt(i)
val pos = indexInChunk(cc, tag.getShort("pos"))
val tile = chunk.chunkTileEntityMap.get(new ChunkPosition(pos.x, pos.y, pos.z))
if(tile.isInstanceOf[TileMultipart])
tickList+=new PartTickEntry(tile.asInstanceOf[TileMultipart].partList(tag.getByte("i")), tag.getLong("time"), false)
}
}
override def unload()
{
if(!tickList.isEmpty)
world.tickChunks-=this
}
} }
def createChunkExtension(chunk:Chunk, world:WorldExtension):ChunkExtension = new ChunkTickScheduler(chunk, world.asInstanceOf[WorldTickScheduler]) override def saveData(data: NBTTagCompound) {
val tagList = new NBTTagList
/** tickList.foreach { e =>
* Start random ticking for a part. Should be called from TMultiPart.onWorldJoin val part = e.part
*/ if (part.tile != null && !e.random) {
def loadRandomTick(part:TRandomUpdateTick) val tag = new NBTTagCompound
{ tag.setShort("pos", indexInChunk(new BlockCoord(part.tile)).toShort)
getExtension(part.tile.getWorldObj).asInstanceOf[WorldTickScheduler].loadRandom(part) tag.setByte("i", part.tile.partList.indexOf(part).toByte)
tag.setLong("time", e.time)
tagList.appendTag(tag)
}
}
if (tagList.tagCount > 0)
data.setTag("multipartTicks", tagList)
} }
/** override def loadData(data: NBTTagCompound) {
* Schedule a tick for part relative to the current time. tickList.clear()
*/ if (!data.hasKey("multipartTicks"))
def scheduleTick(part:TMultiPart, ticks:Int) return
{
getExtension(part.tile.getWorldObj).asInstanceOf[WorldTickScheduler].scheduleTick(part, ticks, false) val tagList = data.getTagList("multipartTicks", 10)
val cc = new ChunkCoordIntPair(0, 0)
for (i <- 0 until tagList.tagCount) {
val tag = tagList.getCompoundTagAt(i)
val pos = indexInChunk(cc, tag.getShort("pos"))
val tile =
chunk.chunkTileEntityMap.get(new ChunkPosition(pos.x, pos.y, pos.z))
if (tile.isInstanceOf[TileMultipart])
tickList += new PartTickEntry(
tile.asInstanceOf[TileMultipart].partList(tag.getByte("i")),
tag.getLong("time"),
false
)
}
} }
/** override def unload() {
* Returns the current scheduler time. Like the world time, but unaffected by the time set command and other things changing time of day. if (!tickList.isEmpty)
* Deprecated in favor of world.getTotalWorldTime world.tickChunks -= this
*/ }
@Deprecated }
def getSchedulerTime(world:World):Long = getExtension(world).asInstanceOf[WorldTickScheduler].schedTime
def createChunkExtension(
chunk: Chunk,
world: WorldExtension
): ChunkExtension =
new ChunkTickScheduler(chunk, world.asInstanceOf[WorldTickScheduler])
/** Start random ticking for a part. Should be called from
* TMultiPart.onWorldJoin
*/
def loadRandomTick(part: TRandomUpdateTick) {
getExtension(part.tile.getWorldObj)
.asInstanceOf[WorldTickScheduler]
.loadRandom(part)
}
/** Schedule a tick for part relative to the current time.
*/
def scheduleTick(part: TMultiPart, ticks: Int) {
getExtension(part.tile.getWorldObj)
.asInstanceOf[WorldTickScheduler]
.scheduleTick(part, ticks, false)
}
/** Returns the current scheduler time. Like the world time, but unaffected by
* the time set command and other things changing time of day. Deprecated in
* favor of world.getTotalWorldTime
*/
@Deprecated
def getSchedulerTime(world: World): Long =
getExtension(world).asInstanceOf[WorldTickScheduler].schedTime
} }
@@ -5,34 +5,42 @@ import scala.collection.mutable.{Map => MMap}
import net.minecraft.world.World import net.minecraft.world.World
import codechicken.multipart.handler.MultipartProxy import codechicken.multipart.handler.MultipartProxy
/** /** In order to maintain tight client/server synchronisation without bandwidth
* In order to maintain tight client/server synchronisation without bandwidth overhead, all data written must be read. * overhead, all data written must be read. Sometimes the client tile is
* Sometimes the client tile is removed from the chunk before the packet arrives. This class maintains a reference to all multipart tiles. * removed from the chunk before the packet arrives. This class maintains a
* The original design placed tiles that were invalidated into a map that was cleared upon arrival of the update packet. * reference to all multipart tiles. The original design placed tiles that were
* Due to other factors that have eluded identification, references to all tiles held until they are replaced or the world is reloaded. * invalidated into a map that was cleared upon arrival of the update packet.
*/ * Due to other factors that have eluded identification, references to all
object TileCache * tiles held until they are replaced or the world is reloaded.
{ */
case class FlaggedTile(t:TileMultipart, removed:Boolean) object TileCache {
case class FlaggedTile(t: TileMultipart, removed: Boolean)
val map = MMap[BlockCoord, FlaggedTile]() val map = MMap[BlockCoord, FlaggedTile]()
def add(t:TileMultipart) = map.put(new BlockCoord(t), FlaggedTile(t, false)) def add(t: TileMultipart) = map.put(new BlockCoord(t), FlaggedTile(t, false))
def remove(t:TileMultipart) = map.put(new BlockCoord(t), FlaggedTile(t, true)) def remove(t: TileMultipart) =
def apply(c:BlockCoord) = map.get(c) map.put(new BlockCoord(t), FlaggedTile(t, true))
def clear() = map.clear() def apply(c: BlockCoord) = map.get(c)
def clear() = map.clear()
def findTile(world:World, c:BlockCoord) = BlockMultipart.getTile(world, c.x, c.y, c.z) match { def findTile(world: World, c: BlockCoord) =
case null => apply(c) match { BlockMultipart.getTile(world, c.x, c.y, c.z) match {
case Some(FlaggedTile(t, rem)) => case null =>
if(!rem) apply(c) match {
MultipartProxy.logger.warn("Client multipart @"+c+" vanished from world but was recovered. If possible causes can be identified, please report to the github issue tracker.") case Some(FlaggedTile(t, rem)) =>
t if (!rem)
case None => MultipartProxy.logger.warn(
throw new RuntimeException("DC: Client multipart @"+c+" not found") "Client multipart @" + c + " vanished from world but was recovered. If possible causes can be identified, please report to the github issue tracker."
case _ => )
null t
case None =>
throw new RuntimeException(
"DC: Client multipart @" + c + " not found"
)
case _ =>
null
} }
case t => t case t => t
} }
} }
File diff suppressed because it is too large. Load diff
@@ -2,23 +2,21 @@ package codechicken.multipart.asm
import java.util.BitSet import java.util.BitSet
object ASMImplicits object ASMImplicits {
{ implicit class ExtBitSet(val bitset: BitSet) extends AnyVal {
implicit class ExtBitSet(val bitset:BitSet) extends AnyVal def set(b: BitSet) = {
{ bitset.clear()
def set(b:BitSet) = { bitset.or(b)
bitset.clear() bitset
bitset.or(b)
bitset
}
def copy = new BitSet().set(bitset)
} }
def nodeName(name:String) = if(name == null) null else name.replace('.', '/') def copy = new BitSet().set(bitset)
}
implicit class ExtClass(val clazz:Class[_]) extends AnyVal def nodeName(name: String) =
{ if (name == null) null else name.replace('.', '/')
def nodeName = ASMImplicits.nodeName(clazz.getName)
} implicit class ExtClass(val clazz: Class[_]) extends AnyVal {
def nodeName = ASMImplicits.nodeName(clazz.getName)
}
} }
File diff suppressed because it is too large. Load diff
@@ -8,80 +8,88 @@ import scala.collection.mutable.ArrayBuffer
import ASMMixinCompiler._ import ASMMixinCompiler._
import ASMImplicits._ import ASMImplicits._
class ASMMixinFactory[T](val baseType:Class[T], private val paramTypes:Class[_]*) class ASMMixinFactory[T](
{ val baseType: Class[T],
private val traitMap = mutable.Map[String, Int]() private val paramTypes: Class[_]*
private val traits = ArrayBuffer[String]() ) {
private val classMap = mutable.Map[BitSet, Constructor[_ <: T]]() private val traitMap = mutable.Map[String, Int]()
private val traits = ArrayBuffer[String]()
private val classMap = mutable.Map[BitSet, Constructor[_ <: T]]()
private var ugenid = 0 private var ugenid = 0
private def nextName() = { private def nextName() = {
val ret = baseType.getSimpleName+"_cmp$$"+ugenid val ret = baseType.getSimpleName + "_cmp$$" + ugenid
ugenid += 1 ugenid += 1
ret ret
}
private def compile(traitSet: BitSet) = {
val seq = Seq.newBuilder[String]
var i = -1
while ({ i = traitSet.nextSetBit(i + 1); i >= 0 })
seq += traits(i)
val c = ASMMixinCompiler
.mixinClasses(nextName(), baseType.nodeName, seq.result())
.asInstanceOf[Class[_ <: T]]
onCompiled(c, traitSet)
c.getDeclaredConstructor(paramTypes: _*)
}
protected def onCompiled(clazz: Class[_ <: T], traitSet: BitSet) {}
protected def autoCompleteJavaTrait(cnode: ClassNode) {}
def construct(traitSet: BitSet, args: Object*) = synchronized {
(classMap.get(traitSet) match {
case Some(c) => c
case None =>
val c = compile(traitSet)
classMap.put(traitSet.copy, c)
c
}).newInstance(args: _*)
}
def getId(s_trait: String) = traitMap(s_trait)
def registerTrait(traitClass: Class[_]): Int = registerTrait(
traitClass.nodeName
)
def registerTrait(s_trait: String): Int = {
val cnode = classNode(s_trait)
if (cnode == null)
throw new ClassNotFoundException(s_trait)
traitMap.get(cnode.name) match {
case Some(id) => return id
case None =>
} }
private def compile(traitSet:BitSet) = { val info = getClassInfo(cnode)
val seq = Seq.newBuilder[String] def concreteParent(info: ClassInfo): ClassInfo = info.superClass.map {
var i = -1 case i if i.isTrait => concreteParent(i)
while({i = traitSet.nextSetBit(i+1); i >= 0}) case i => i
seq += traits(i) }.get
val c = ASMMixinCompiler.mixinClasses(nextName(), baseType.nodeName, seq.result()).asInstanceOf[Class[_ <: T]] val parentName = concreteParent(info).name
onCompiled(c, traitSet) def checkParent(info: ClassInfo): Boolean =
c.getDeclaredConstructor(paramTypes:_*) info.name == parentName || info.superClass.exists(checkParent)
if (!checkParent(getClassInfo(baseType)))
throw new IllegalArgumentException(
baseType.nodeName + " does not extend parent " + parentName + " of mixin trait " + s_trait
)
if (info.isTrait) {
registerScalaTrait(cnode)
} else {
autoCompleteJavaTrait(cnode)
registerJavaTrait(cnode)
} }
protected def onCompiled(clazz:Class[_ <: T], traitSet:BitSet){} val id = traits.size
protected def autoCompleteJavaTrait(cnode:ClassNode){} traits += cnode.name
traitMap.put(cnode.name, id)
def construct(traitSet:BitSet, args:Object*) = synchronized { id
(classMap.get(traitSet) match { }
case Some(c) => c
case None =>
val c = compile(traitSet)
classMap.put(traitSet.copy, c)
c
}).newInstance(args: _*)
}
def getId(s_trait:String) = traitMap(s_trait)
def registerTrait(traitClass:Class[_]):Int = registerTrait(traitClass.nodeName)
def registerTrait(s_trait:String):Int = {
val cnode = classNode(s_trait)
if(cnode == null)
throw new ClassNotFoundException(s_trait)
traitMap.get(cnode.name) match {
case Some(id) => return id
case None =>
}
val info = getClassInfo(cnode)
def concreteParent(info:ClassInfo):ClassInfo = info.superClass.map {
case i if i.isTrait => concreteParent(i)
case i => i
}.get
val parentName = concreteParent(info).name
def checkParent(info:ClassInfo):Boolean = info.name == parentName || info.superClass.exists(checkParent)
if(!checkParent(getClassInfo(baseType)))
throw new IllegalArgumentException(baseType.nodeName+" does not extend parent "+parentName+" of mixin trait "+s_trait)
if(info.isTrait) {
registerScalaTrait(cnode)
}
else {
autoCompleteJavaTrait(cnode)
registerJavaTrait(cnode)
}
val id = traits.size
traits += cnode.name
traitMap.put(cnode.name, id)
id
}
} }
@@ -190,22 +190,20 @@ object ByteCodecs {
def encode(xs: Array[Byte]): Array[Byte] = avoidZero(encode8to7(xs)) def encode(xs: Array[Byte]): Array[Byte] = avoidZero(encode8to7(xs))
/** /** Destructively decodes array xs and returns the length of the decoded
* Destructively decodes array xs and returns the length of the decoded array. * array.
* *
* Sometimes returns (length+1) of the decoded array. Example: * Sometimes returns (length+1) of the decoded array. Example:
* *
* scala> val enc = scala.reflect.generic.ByteCodecs.encode(Array(1,2,3)) * scala> val enc = scala.reflect.generic.ByteCodecs.encode(Array(1,2,3))
* enc: Array[Byte] = Array(2, 5, 13, 1) * enc: Array[Byte] = Array(2, 5, 13, 1)
* *
* scala> scala.reflect.generic.ByteCodecs.decode(enc) * scala> scala.reflect.generic.ByteCodecs.decode(enc) res43: Int = 4
* res43: Int = 4 *
* * scala> enc res44: Array[Byte] = Array(1, 2, 3, 0)
* scala> enc *
* res44: Array[Byte] = Array(1, 2, 3, 0) * However, this does not always happen.
* */
* However, this does not always happen.
*/
def decode(xs: Array[Byte]): Int = { def decode(xs: Array[Byte]): Int = {
val len = regenerateZero(xs) val len = regenerateZero(xs)
decode7to8(xs, len) decode7to8(xs, len)
@@ -12,166 +12,237 @@ import ASMImplicits._
import scala.collection.JavaConversions._ import scala.collection.JavaConversions._
object MultipartMixinFactory extends ASMMixinFactory(classOf[TileMultipart]) object MultipartMixinFactory extends ASMMixinFactory(classOf[TileMultipart]) {
{ override protected def autoCompleteJavaTrait(cnode: ClassNode) {
override protected def autoCompleteJavaTrait(cnode: ClassNode) if (
!cnode.fields.isEmpty && findMethod(
new ObfMapping(
cnode.name,
"copyFrom",
"(Lcodechicken/multipart/TileMultipart;)V"
),
cnode
) == null
) {
val mv = cnode.visitMethod(
ACC_PUBLIC,
"copyFrom",
"(Lcodechicken/multipart/TileMultipart;)V",
null,
null
)
mv.visitVarInsn(ALOAD, 0)
mv.visitVarInsn(ALOAD, 1)
mv.visitMethodInsn(
INVOKESPECIAL,
"codechicken/multipart/TileMultipart",
"copyFrom",
"(Lcodechicken/multipart/TileMultipart;)V"
)
mv.visitVarInsn(ALOAD, 1)
mv.visitTypeInsn(INSTANCEOF, cnode.name)
val end = new Label()
mv.visitJumpInsn(IFEQ, end)
cnode.fields.foreach { f =>
mv.visitVarInsn(ALOAD, 0)
mv.visitVarInsn(ALOAD, 1)
mv.visitFieldInsn(GETFIELD, cnode.name, f.name, f.desc)
mv.visitFieldInsn(PUTFIELD, cnode.name, f.name, f.desc)
}
mv.visitLabel(end)
mv.visitInsn(RETURN)
mv.visitMaxs(2, 2)
}
}
def generatePassThroughTrait(s_interface: String): String = {
val iname = nodeName(s_interface)
val tname = {
var simpleName = iname.substring(iname.lastIndexOf('/') + 1)
if (simpleName.startsWith("I")) simpleName = simpleName.substring(1)
"T" + simpleName + "$$PassThrough"
}
val vname = "impl"
val idesc = "L" + iname + ";"
val inode = classNode(s_interface)
if (inode == null) {
logger.error(
"Unable to generate pass through trait for: " + s_interface + " class not found."
)
return null
}
if ((inode.access & ACC_INTERFACE) == 0)
throw new IllegalArgumentException(s_interface + " is not an interface.")
val cw = new CC_ClassWriter(0)
var mv: MethodVisitor = null
var fv: FieldVisitor = null
cw.visit(
V1_6,
ACC_PUBLIC | ACC_SUPER,
tname,
null,
"codechicken/multipart/TileMultipart",
Array(iname)
)
{ {
if(!cnode.fields.isEmpty && findMethod(new ObfMapping(cnode.name, "copyFrom", "(Lcodechicken/multipart/TileMultipart;)V"), cnode) == null) fv = cw.visitField(ACC_PRIVATE, vname, idesc, null, null)
{ fv.visitEnd()
val mv = cnode.visitMethod(ACC_PUBLIC, "copyFrom", "(Lcodechicken/multipart/TileMultipart;)V", null, null) }
mv.visitVarInsn(ALOAD, 0) {
mv.visitVarInsn(ALOAD, 1) mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null)
mv.visitMethodInsn(INVOKESPECIAL, "codechicken/multipart/TileMultipart", "copyFrom", "(Lcodechicken/multipart/TileMultipart;)V") mv.visitCode()
mv.visitVarInsn(ALOAD, 0)
mv.visitVarInsn(ALOAD, 1) mv.visitMethodInsn(
mv.visitTypeInsn(INSTANCEOF, cnode.name) INVOKESPECIAL,
val end = new Label() "codechicken/multipart/TileMultipart",
mv.visitJumpInsn(IFEQ, end) "<init>",
"()V"
cnode.fields.foreach{ f => )
mv.visitVarInsn(ALOAD, 0) mv.visitInsn(RETURN)
mv.visitVarInsn(ALOAD, 1) mv.visitMaxs(1, 1)
mv.visitFieldInsn(GETFIELD, cnode.name, f.name, f.desc) mv.visitEnd()
mv.visitFieldInsn(PUTFIELD, cnode.name, f.name, f.desc) }
} {
mv = cw.visitMethod(
mv.visitLabel(end) ACC_PUBLIC,
mv.visitInsn(RETURN) "bindPart",
mv.visitMaxs(2, 2) "(Lcodechicken/multipart/TMultiPart;)V",
} null,
null
)
mv.visitCode()
mv.visitVarInsn(ALOAD, 0)
mv.visitVarInsn(ALOAD, 1)
mv.visitMethodInsn(
INVOKESPECIAL,
"codechicken/multipart/TileMultipart",
"bindPart",
"(Lcodechicken/multipart/TMultiPart;)V"
)
mv.visitVarInsn(ALOAD, 1)
mv.visitTypeInsn(INSTANCEOF, iname)
val l2 = new Label()
mv.visitJumpInsn(IFEQ, l2)
val l3 = new Label()
mv.visitLabel(l3)
mv.visitVarInsn(ALOAD, 0)
mv.visitVarInsn(ALOAD, 1)
mv.visitTypeInsn(CHECKCAST, iname)
mv.visitFieldInsn(PUTFIELD, tname, vname, idesc)
mv.visitLabel(l2)
mv.visitFrame(F_SAME, 0, null, 0, null)
mv.visitInsn(RETURN)
mv.visitMaxs(2, 2)
mv.visitEnd()
}
{
mv = cw.visitMethod(
ACC_PUBLIC,
"partRemoved",
"(Lcodechicken/multipart/TMultiPart;I)V",
null,
null
)
mv.visitCode()
mv.visitVarInsn(ALOAD, 0)
mv.visitVarInsn(ALOAD, 1)
mv.visitVarInsn(ILOAD, 2)
mv.visitMethodInsn(
INVOKESPECIAL,
"codechicken/multipart/TileMultipart",
"partRemoved",
"(Lcodechicken/multipart/TMultiPart;I)V"
)
mv.visitVarInsn(ALOAD, 1)
mv.visitVarInsn(ALOAD, 0)
mv.visitFieldInsn(GETFIELD, tname, vname, idesc)
val l2 = new Label()
mv.visitJumpInsn(IF_ACMPNE, l2)
val l3 = new Label()
mv.visitLabel(l3)
mv.visitVarInsn(ALOAD, 0)
mv.visitInsn(ACONST_NULL)
mv.visitFieldInsn(PUTFIELD, tname, vname, idesc)
mv.visitLabel(l2)
mv.visitFrame(F_SAME, 0, null, 0, null)
mv.visitInsn(RETURN)
mv.visitMaxs(3, 3)
mv.visitEnd()
}
{
mv = cw.visitMethod(
ACC_PUBLIC,
"canAddPart",
"(Lcodechicken/multipart/TMultiPart;)Z",
null,
null
)
mv.visitCode()
mv.visitVarInsn(ALOAD, 0)
mv.visitFieldInsn(GETFIELD, tname, vname, idesc)
val l1 = new Label()
mv.visitJumpInsn(IFNULL, l1)
mv.visitVarInsn(ALOAD, 1)
mv.visitTypeInsn(INSTANCEOF, iname)
mv.visitJumpInsn(IFEQ, l1)
val l2 = new Label()
mv.visitLabel(l2)
mv.visitInsn(ICONST_0)
mv.visitInsn(IRETURN)
mv.visitLabel(l1)
mv.visitFrame(F_SAME, 0, null, 0, null)
mv.visitVarInsn(ALOAD, 0)
mv.visitVarInsn(ALOAD, 1)
mv.visitMethodInsn(
INVOKESPECIAL,
"codechicken/multipart/TileMultipart",
"canAddPart",
"(Lcodechicken/multipart/TMultiPart;)Z"
)
mv.visitInsn(IRETURN)
mv.visitMaxs(2, 2)
mv.visitEnd()
} }
def generatePassThroughTrait(s_interface:String):String = def methods(cnode: ClassNode): Map[String, MethodNode] = {
{ val m = cnode.methods.map(m => (m.name + m.desc, m)).toMap
val iname = nodeName(s_interface) if (cnode.interfaces != null)
val tname = { m ++ cnode.interfaces.flatMap(i => methods(classNode(i)))
var simpleName = iname.substring(iname.lastIndexOf('/')+1) else
if(simpleName.startsWith("I")) simpleName = simpleName.substring(1) m
"T" + simpleName + "$$PassThrough"
}
val vname = "impl"
val idesc = "L"+iname+";"
val inode = classNode(s_interface)
if(inode == null) {
logger.error("Unable to generate pass through trait for: "+s_interface+" class not found.")
return null
}
if((inode.access&ACC_INTERFACE) == 0) throw new IllegalArgumentException(s_interface+" is not an interface.")
val cw = new CC_ClassWriter(0)
var mv:MethodVisitor = null
var fv:FieldVisitor = null
cw.visit(V1_6, ACC_PUBLIC|ACC_SUPER, tname, null, "codechicken/multipart/TileMultipart", Array(iname))
{
fv = cw.visitField(ACC_PRIVATE, vname, idesc, null, null)
fv.visitEnd()
}
{
mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null)
mv.visitCode()
mv.visitVarInsn(ALOAD, 0)
mv.visitMethodInsn(INVOKESPECIAL, "codechicken/multipart/TileMultipart", "<init>", "()V")
mv.visitInsn(RETURN)
mv.visitMaxs(1, 1)
mv.visitEnd()
}
{
mv = cw.visitMethod(ACC_PUBLIC, "bindPart", "(Lcodechicken/multipart/TMultiPart;)V", null, null)
mv.visitCode()
mv.visitVarInsn(ALOAD, 0)
mv.visitVarInsn(ALOAD, 1)
mv.visitMethodInsn(INVOKESPECIAL, "codechicken/multipart/TileMultipart", "bindPart", "(Lcodechicken/multipart/TMultiPart;)V")
mv.visitVarInsn(ALOAD, 1)
mv.visitTypeInsn(INSTANCEOF, iname)
val l2 = new Label()
mv.visitJumpInsn(IFEQ, l2)
val l3 = new Label()
mv.visitLabel(l3)
mv.visitVarInsn(ALOAD, 0)
mv.visitVarInsn(ALOAD, 1)
mv.visitTypeInsn(CHECKCAST, iname)
mv.visitFieldInsn(PUTFIELD, tname, vname, idesc)
mv.visitLabel(l2)
mv.visitFrame(F_SAME, 0, null, 0, null)
mv.visitInsn(RETURN)
mv.visitMaxs(2, 2)
mv.visitEnd()
}
{
mv = cw.visitMethod(ACC_PUBLIC, "partRemoved", "(Lcodechicken/multipart/TMultiPart;I)V", null, null)
mv.visitCode()
mv.visitVarInsn(ALOAD, 0)
mv.visitVarInsn(ALOAD, 1)
mv.visitVarInsn(ILOAD, 2)
mv.visitMethodInsn(INVOKESPECIAL, "codechicken/multipart/TileMultipart", "partRemoved", "(Lcodechicken/multipart/TMultiPart;I)V")
mv.visitVarInsn(ALOAD, 1)
mv.visitVarInsn(ALOAD, 0)
mv.visitFieldInsn(GETFIELD, tname, vname, idesc)
val l2 = new Label()
mv.visitJumpInsn(IF_ACMPNE, l2)
val l3 = new Label()
mv.visitLabel(l3)
mv.visitVarInsn(ALOAD, 0)
mv.visitInsn(ACONST_NULL)
mv.visitFieldInsn(PUTFIELD, tname, vname, idesc)
mv.visitLabel(l2)
mv.visitFrame(F_SAME, 0, null, 0, null)
mv.visitInsn(RETURN)
mv.visitMaxs(3, 3)
mv.visitEnd()
}
{
mv = cw.visitMethod(ACC_PUBLIC, "canAddPart", "(Lcodechicken/multipart/TMultiPart;)Z", null, null)
mv.visitCode()
mv.visitVarInsn(ALOAD, 0)
mv.visitFieldInsn(GETFIELD, tname, vname, idesc)
val l1 = new Label()
mv.visitJumpInsn(IFNULL, l1)
mv.visitVarInsn(ALOAD, 1)
mv.visitTypeInsn(INSTANCEOF, iname)
mv.visitJumpInsn(IFEQ, l1)
val l2 = new Label()
mv.visitLabel(l2)
mv.visitInsn(ICONST_0)
mv.visitInsn(IRETURN)
mv.visitLabel(l1)
mv.visitFrame(F_SAME, 0, null, 0, null)
mv.visitVarInsn(ALOAD, 0)
mv.visitVarInsn(ALOAD, 1)
mv.visitMethodInsn(INVOKESPECIAL, "codechicken/multipart/TileMultipart", "canAddPart", "(Lcodechicken/multipart/TMultiPart;)Z")
mv.visitInsn(IRETURN)
mv.visitMaxs(2, 2)
mv.visitEnd()
}
def methods(cnode:ClassNode):Map[String, MethodNode] =
{
val m = cnode.methods.map(m => (m.name+m.desc, m)).toMap
if(cnode.interfaces != null)
m++cnode.interfaces.flatMap(i => methods(classNode(i)))
else
m
}
def generatePassThroughMethod(m:MethodNode)
{
mv = cw.visitMethod(ACC_PUBLIC, m.name, m.desc, m.signature, Array(m.exceptions:_*))
mv.visitVarInsn(ALOAD, 0)
mv.visitFieldInsn(GETFIELD, tname, vname, idesc)
finishBridgeCall(mv, m.desc, INVOKEINTERFACE, iname, m.name, m.desc)
}
methods(inode).values.foreach(generatePassThroughMethod)
cw.visitEnd()
internalDefine(tname, cw.toByteArray)
registerTrait(tname)
return tname
} }
override protected def onCompiled(clazz: Class[_ <: TileMultipart], traitSet:BitSet) = def generatePassThroughMethod(m: MethodNode) {
MultipartGenerator.registerTileClass(clazz, traitSet) mv = cw.visitMethod(
ACC_PUBLIC,
m.name,
m.desc,
m.signature,
Array(m.exceptions: _*)
)
mv.visitVarInsn(ALOAD, 0)
mv.visitFieldInsn(GETFIELD, tname, vname, idesc)
finishBridgeCall(mv, m.desc, INVOKEINTERFACE, iname, m.name, m.desc)
}
methods(inode).values.foreach(generatePassThroughMethod)
cw.visitEnd()
internalDefine(tname, cw.toByteArray)
registerTrait(tname)
return tname
}
override protected def onCompiled(
clazz: Class[_ <: TileMultipart],
traitSet: BitSet
) =
MultipartGenerator.registerTileClass(clazz, traitSet)
} }
@@ -10,344 +10,360 @@ import scala.collection.JavaConversions._
import ScalaSignature._ import ScalaSignature._
object ScalaSignature object ScalaSignature {
{ object Bytes {
object Bytes def apply(arr: Array[Byte]): Bytes = Bytes(arr, 0, arr.length)
{ }
def apply(arr: Array[Byte]):Bytes = Bytes(arr, 0, arr.length)
}
case class Bytes(arr: Array[Byte], pos: Int, len: Int) case class Bytes(arr: Array[Byte], pos: Int, len: Int) {
{ def reader = new ByteCodeReader(this)
def reader = new ByteCodeReader(this) def section = arr.drop(pos).take(len)
def section = arr.drop(pos).take(len) }
}
trait Flags trait Flags {
{ def hasFlag(flag: Int): Boolean
def hasFlag(flag: Int): Boolean
def isPrivate = hasFlag(0x00000004) def isPrivate = hasFlag(0x00000004)
def isProtected = hasFlag(0x00000008) def isProtected = hasFlag(0x00000008)
def isAbstract = hasFlag(0x00000080) def isAbstract = hasFlag(0x00000080)
def isDeferred = hasFlag(0x00000100) def isDeferred = hasFlag(0x00000100)
//abstract for methods // abstract for methods
def isMethod = hasFlag(0x00000200) def isMethod = hasFlag(0x00000200)
def isModule = hasFlag(0x00000400) def isModule = hasFlag(0x00000400)
//object module class // object module class
def isInterface = hasFlag(0x00000800) def isInterface = hasFlag(0x00000800)
def isParam = hasFlag(0x00002000) def isParam = hasFlag(0x00002000)
def isStatic = hasFlag(0x00800000) def isStatic = hasFlag(0x00800000)
def isTrait = hasFlag(0x02000000) def isTrait = hasFlag(0x02000000)
def isAccessor = hasFlag(0x08000000) def isAccessor = hasFlag(0x08000000)
} }
} }
class ScalaSignature(val bytes: Bytes) class ScalaSignature(val bytes: Bytes) {
{ val major = bytes.arr(0).toInt
val major = bytes.arr(0).toInt val minor = bytes.arr(1).toInt
val minor = bytes.arr(1).toInt val table = {
val table = { val bcr = bytes.reader
val bcr = bytes.reader bcr.pos = 2
bcr.pos = 2 Array.tabulate(bcr.readNat) { i =>
Array.tabulate(bcr.readNat){ i => val start = bcr.pos
val start = bcr.pos val tpe = bcr.readByte
val tpe = bcr.readByte val len = bcr.readNat
val len = bcr.readNat bcr.advance(len)(new SigEntry(i, start, Bytes(bytes.arr, bcr.pos, len)))
bcr.advance(len)(new SigEntry(i, start, Bytes(bytes.arr, bcr.pos, len))) }
} }
trait SymbolRef extends Flags {
def full: String
def flags: Int
def hasFlag(flag: Int) = (flags & flag) != 0
}
trait ClassSymbolRef extends SymbolRef {
def name: String
def owner: SymbolRef
def flags: Int
def infoId: Int
def full = owner.full + "." + name
override def toString = getClass.getName.replaceAll(".+\\$", "") +
"(" + name + "," + owner + "," + flags.toHexString + "," + infoId + ")"
def isObject = false
def info: ClassType = evalT(infoId)
def jParent = info.parent.jName
def jInterfaces = info.interfaces.map(_.jName)
}
case class ClassSymbol(
name: String,
owner: SymbolRef,
flags: Int,
infoId: Int
) extends ClassSymbolRef
case class ObjectSymbol(
name: String,
owner: SymbolRef,
flags: Int,
infoId: Int
) extends ClassSymbolRef {
override def isObject = true
}
case class MethodSymbol(
name: String,
owner: SymbolRef,
flags: Int,
infoId: Int
) extends SymbolRef {
override def toString =
"MethodSymbol(" + name + "," + owner + "," + flags.toHexString + "," + infoId + ")"
def full = owner.full + "." + name
def info: TMethodType = evalT(infoId)
def jDesc = info.jDesc
}
case class ExternalSymbol(name: String) extends SymbolRef {
override def toString = name
def full = name
def flags = 0
}
case object NoSymbol extends SymbolRef {
def full = "<no symbol>"
def flags = 0
}
trait TMethodType {
def jDesc = "(" + params
.map(m => m.info.returnType.jDesc)
.mkString + ")" + returnType.jDesc
def returnType: TypeRef
def params: List[MethodSymbol]
}
case class ClassType(owner: SymbolRef, parents: List[TypeRef]) {
def parent = parents.head
def interfaces = parents.drop(1)
}
case class MethodType(returnType: TypeRef, params: List[MethodSymbol])
extends TMethodType
case class ParameterlessType(returnType: TypeRef) extends TMethodType {
def params = List()
}
trait TypeRef {
def sym: SymbolRef
def name = sym.full
def jName = name.replace('.', '/') match {
case "scala/AnyRef" | "scala/Any" => "java/lang/Object"
case s => s
} }
trait SymbolRef extends Flags def jDesc = name match {
{ case "scala.Array" => null
def full: String case "scala.Long" => "J"
def flags: Int case "scala.Int" => "I"
def hasFlag(flag: Int) = (flags & flag) != 0 case "scala.Short" => "S"
case "scala.Byte" => "B"
case "scala.Double" => "D"
case "scala.Float" => "F"
case "scala.Boolean" => "Z"
case "scala.Unit" => "V"
case _ => "L" + jName + ";"
} }
}
trait ClassSymbolRef extends SymbolRef case class TypeRefType(owner: TypeRef, sym: SymbolRef, typArgs: List[TypeRef])
{ extends TMethodType
def name: String with TypeRef {
def owner: SymbolRef def params = List()
def flags: Int
def infoId: Int
def full = owner.full + "." + name def returnType = this
override def toString = getClass.getName.replaceAll(".+\\$", "") +
"(" + name + "," + owner + "," + flags.toHexString + "," + infoId + ")"
def isObject = false override def jDesc = name match {
def info: ClassType = evalT(infoId) case "scala.Array" => "[" + typArgs(0).jDesc
def jParent = info.parent.jName case _ => super.jDesc
def jInterfaces = info.interfaces.map(_.jName)
} }
}
case class ClassSymbol(name: String, owner: SymbolRef, flags: Int, infoId: Int) extends ClassSymbolRef case class ThisType(sym: SymbolRef) extends TypeRef
case class ObjectSymbol(name: String, owner: SymbolRef, flags: Int, infoId: Int) extends ClassSymbolRef case class SingleType(owner: TypeRef, sym: SymbolRef) extends TypeRef {
{ override def jName = super.jName + "$"
override def isObject = true }
case object NoType extends TypeRef {
def sym = null
override def name = "<no type>"
}
case class SigEntry(index: Int, start: Int, bytes: Bytes) {
def id = bytes.arr(start)
def delete() = bytes.arr(start) = 3
override def toString =
"SigEntry(" + index + "," + id + "," + bytes.len + " bytes)"
}
trait Literal {
def value: Any
}
case class BooleanLiteral(value: Boolean) extends Literal
case class ByteLiteral(value: Byte) extends Literal
case class ShortLiteral(value: Short) extends Literal
case class CharLiteral(value: Char) extends Literal
case class IntLiteral(value: Int) extends Literal
case class LongLiteral(value: Long) extends Literal
case class FloatLiteral(value: Float) extends Literal
case class DoubleLiteral(value: Double) extends Literal
case object NullLiteral extends Literal {
override def value = null
}
case class StringLiteral(value: String) extends Literal
case class TypeLiteral(value: TypeRef) extends Literal
case class EnumLiteral(value: ExternalSymbol) extends Literal
case class ArrayLiteral(value: List[_]) extends Literal
case class AnnotationInfo(
owner: SymbolRef,
annType: TypeRef,
values: Map[String, Literal]
) {
def getValue[T](name: String) = values(name).asInstanceOf[T]
}
def evalS(i: Int): String = {
val e = table(i)
val bc = e.bytes
val bcr = bc.reader
e.id match {
case 1 | 2 => bcr.readString(bc.len)
case 3 => NoSymbol.full
case 9 | 10 =>
var s = evalS(bcr.readNat)
if (bc.pos + bc.len > bcr.pos)
s = evalS(bcr.readNat) + "." + s
s
} }
}
case class MethodSymbol(name: String, owner: SymbolRef, flags: Int, infoId: Int) extends SymbolRef def evalT[T](i: Int) = eval(i).asInstanceOf[T]
{
override def toString = "MethodSymbol(" + name + "," + owner + "," + flags.toHexString + "," + infoId + ")"
def full = owner.full + "." + name
def info: TMethodType = evalT(infoId) def evalList[T](bcr: ByteCodeReader) = {
def jDesc = info.jDesc val l = List.newBuilder
while (bcr.more)
l += evalT(bcr.readNat)
l.result()
}
def eval(i: Int): Any = {
// only parse the ones that matter for this project
val e = table(i)
val bcr = e.bytes.reader
def nat = bcr.readNat
def evalS = this.evalS(nat)
def evalT[T] = this.evalT[T](nat)
def evalList[T] = this.evalList[T](bcr)
e.id match {
case 1 | 2 => this.evalS(i)
case 3 => NoSymbol
case 6 => ClassSymbol(evalS, evalT, nat, nat)
case 7 => ObjectSymbol(evalS, evalT, nat, nat)
case 8 => MethodSymbol(evalS, evalT, nat, nat)
case 9 | 10 => ExternalSymbol(this.evalS(i))
case 11 | 12 => NoType // 12 is actually NoPrefixType (no lower bound)
case 13 => ThisType(evalT)
case 14 => SingleType(evalT, evalT)
case 16 => TypeRefType(evalT, evalT, evalList)
case 19 => ClassType(evalT, evalList)
case 20 => MethodType(evalT, evalList)
case 21 | 48 =>
ParameterlessType(
evalT
) // 48 is actually a bounded super type, but it should work fine for this project
case 25 => BooleanLiteral(bcr.readLong != 0)
case 26 => ByteLiteral(bcr.readLong.toByte)
case 27 => ShortLiteral(bcr.readLong.toShort)
case 28 => CharLiteral(bcr.readLong.toChar)
case 29 => IntLiteral(bcr.readLong.toInt)
case 30 => LongLiteral(bcr.readLong)
case 31 =>
FloatLiteral(java.lang.Float.intBitsToFloat(bcr.readLong.toInt))
case 32 => DoubleLiteral(java.lang.Double.longBitsToDouble(bcr.readLong))
case 33 => StringLiteral(evalS)
case 34 => NullLiteral
case 35 => TypeLiteral(evalT)
case 36 => EnumLiteral(evalT)
case 40 =>
AnnotationInfo(
evalT,
evalT,
evalList.grouped(2).map(g => (g(0), g(1))).toMap
)
case 44 => ArrayLiteral(evalList)
case _ => e
} }
}
case class ExternalSymbol(name: String) extends SymbolRef def collect[T](id: Int) = (0 until table.length).collect {
{ case i if table(i).id == id => evalT(i): T
override def toString = name }
def full = name
def flags = 0
}
case object NoSymbol extends SymbolRef def findObject(name: String) = collect[ObjectSymbol](7).find(_.full == name)
{ def findClass(name: String) =
def full = "<no symbol>" collect[ClassSymbol](6).find(c => !c.isModule && c.full == name)
def flags = 0
}
trait TMethodType
{
def jDesc = "(" + params.map(m => m.info.returnType.jDesc).mkString + ")" + returnType.jDesc
def returnType: TypeRef
def params: List[MethodSymbol]
}
case class ClassType(owner: SymbolRef, parents: List[TypeRef])
{
def parent = parents.head
def interfaces = parents.drop(1)
}
case class MethodType(returnType: TypeRef, params: List[MethodSymbol]) extends TMethodType
case class ParameterlessType(returnType: TypeRef) extends TMethodType
{
def params = List()
}
trait TypeRef
{
def sym: SymbolRef
def name = sym.full
def jName = name.replace('.', '/') match {
case "scala/AnyRef" | "scala/Any" => "java/lang/Object"
case s => s
}
def jDesc = name match {
case "scala.Array" => null
case "scala.Long" => "J"
case "scala.Int" => "I"
case "scala.Short" => "S"
case "scala.Byte" => "B"
case "scala.Double" => "D"
case "scala.Float" => "F"
case "scala.Boolean" => "Z"
case "scala.Unit" => "V"
case _ => "L" + jName + ";"
}
}
case class TypeRefType(owner: TypeRef, sym: SymbolRef, typArgs: List[TypeRef]) extends TMethodType with TypeRef
{
def params = List()
def returnType = this
override def jDesc = name match {
case "scala.Array" => "[" + typArgs(0).jDesc
case _ => super.jDesc
}
}
case class ThisType(sym: SymbolRef) extends TypeRef
case class SingleType(owner: TypeRef, sym: SymbolRef) extends TypeRef
{
override def jName = super.jName + "$"
}
case object NoType extends TypeRef
{
def sym = null
override def name = "<no type>"
}
case class SigEntry(index:Int, start: Int, bytes: Bytes)
{
def id = bytes.arr(start)
def delete() = bytes.arr(start) = 3
override def toString = "SigEntry("+index+","+id+","+bytes.len+" bytes)"
}
trait Literal
{
def value:Any
}
case class BooleanLiteral(value:Boolean) extends Literal
case class ByteLiteral(value:Byte) extends Literal
case class ShortLiteral(value:Short) extends Literal
case class CharLiteral(value:Char) extends Literal
case class IntLiteral(value:Int) extends Literal
case class LongLiteral(value:Long) extends Literal
case class FloatLiteral(value:Float) extends Literal
case class DoubleLiteral(value:Double) extends Literal
case object NullLiteral extends Literal
{
override def value = null
}
case class StringLiteral(value:String) extends Literal
case class TypeLiteral(value:TypeRef) extends Literal
case class EnumLiteral(value:ExternalSymbol) extends Literal
case class ArrayLiteral(value:List[_]) extends Literal
case class AnnotationInfo(owner:SymbolRef, annType:TypeRef, values:Map[String, Literal])
{
def getValue[T](name:String) = values(name).asInstanceOf[T]
}
def evalS(i: Int): String = {
val e = table(i)
val bc = e.bytes
val bcr = bc.reader
e.id match {
case 1 | 2 => bcr.readString(bc.len)
case 3 => NoSymbol.full
case 9 | 10 =>
var s = evalS(bcr.readNat)
if (bc.pos + bc.len > bcr.pos)
s = evalS(bcr.readNat) + "." + s
s
}
}
def evalT[T](i: Int) = eval(i).asInstanceOf[T]
def evalList[T](bcr: ByteCodeReader) = {
val l = List.newBuilder
while (bcr.more)
l += evalT(bcr.readNat)
l.result()
}
def eval(i: Int): Any = {
//only parse the ones that matter for this project
val e = table(i)
val bcr = e.bytes.reader
def nat = bcr.readNat
def evalS = this.evalS(nat)
def evalT[T] = this.evalT[T](nat)
def evalList[T] = this.evalList[T](bcr)
e.id match {
case 1 | 2 => this.evalS(i)
case 3 => NoSymbol
case 6 => ClassSymbol(evalS, evalT, nat, nat)
case 7 => ObjectSymbol(evalS, evalT, nat, nat)
case 8 => MethodSymbol(evalS, evalT, nat, nat)
case 9 | 10 => ExternalSymbol(this.evalS(i))
case 11 | 12 => NoType //12 is actually NoPrefixType (no lower bound)
case 13 => ThisType(evalT)
case 14 => SingleType(evalT, evalT)
case 16 => TypeRefType(evalT, evalT, evalList)
case 19 => ClassType(evalT, evalList)
case 20 => MethodType(evalT, evalList)
case 21 | 48 => ParameterlessType(evalT) //48 is actually a bounded super type, but it should work fine for this project
case 25 => BooleanLiteral(bcr.readLong != 0)
case 26 => ByteLiteral(bcr.readLong.toByte)
case 27 => ShortLiteral(bcr.readLong.toShort)
case 28 => CharLiteral(bcr.readLong.toChar)
case 29 => IntLiteral(bcr.readLong.toInt)
case 30 => LongLiteral(bcr.readLong)
case 31 => FloatLiteral(java.lang.Float.intBitsToFloat(bcr.readLong.toInt))
case 32 => DoubleLiteral(java.lang.Double.longBitsToDouble(bcr.readLong))
case 33 => StringLiteral(evalS)
case 34 => NullLiteral
case 35 => TypeLiteral(evalT)
case 36 => EnumLiteral(evalT)
case 40 => AnnotationInfo(evalT, evalT, evalList.grouped(2).map(g => (g(0), g(1))).toMap)
case 44 => ArrayLiteral(evalList)
case _ => e
}
}
def collect[T](id: Int) = (0 until table.length).collect {
case i if table(i).id == id => evalT(i): T
}
def findObject(name: String) = collect[ObjectSymbol](7).find(_.full == name)
def findClass(name: String) = collect[ClassSymbol](6).find(c => !c.isModule && c.full == name)
} }
class ByteCodeReader(val bc: Bytes) class ByteCodeReader(val bc: Bytes) {
{ var pos = bc.pos
var pos = bc.pos
def more = pos < bc.pos + bc.len def more = pos < bc.pos + bc.len
def readString(len: Int) = advance(len)(new String(bc.arr.drop(pos).take(len))) def readString(len: Int) =
advance(len)(new String(bc.arr.drop(pos).take(len)))
def readByte = advance(1)(bc.arr(pos)) def readByte = advance(1)(bc.arr(pos))
def readNat = { def readNat = {
var r = 0 var r = 0
var b = 0 var b = 0
do { do {
b = readByte b = readByte
r = r << 7 | b & 0x7F r = r << 7 | b & 0x7f
} } while ((b & 0x80) != 0)
while ((b & 0x80) != 0) r
r }
def readLong = {
var l = 0L
while (more) {
l <<= 8
l |= readByte & 0xff
} }
l
}
def readLong = { def advance[A](len: Int)(r: A) = {
var l = 0L if (pos + len > bc.pos + bc.len)
while(more) { throw new IllegalArgumentException("Ran off the end of bytecode")
l <<= 8 pos += len
l |= readByte & 0xFF r
} }
l
}
def advance[A](len: Int)(r: A) = {
if (pos + len > bc.pos + bc.len)
throw new IllegalArgumentException("Ran off the end of bytecode")
pos += len
r
}
} }
object ScalaSigReader object ScalaSigReader {
{ def decode(s: String) = {
def decode(s: String) = { val bytes = s.getBytes
val bytes = s.getBytes bytes take ByteCodecs.decode(bytes)
bytes take ByteCodecs.decode(bytes) }
def encode(b: Array[Byte]) = {
val bytes = ByteCodecs.encode8to7(b)
var i = 0
while (i < bytes.length) {
bytes(i) = ((bytes(i) + 1) & 0x7f).toByte
i += 1
} }
new String(bytes.take(bytes.length - 1), "UTF-8")
}
def encode(b: Array[Byte]) = { def read(ann: AnnotationNode): ScalaSignature = new ScalaSignature(
val bytes = ByteCodecs.encode8to7(b) Bytes(decode(ann.values.get(1).asInstanceOf[String]))
var i = 0 )
while (i < bytes.length) {
bytes(i) = ((bytes(i) + 1) & 0x7F).toByte
i += 1
}
new String(bytes.take(bytes.length - 1), "UTF-8")
}
def read(ann: AnnotationNode): ScalaSignature = new ScalaSignature(Bytes(decode(ann.values.get(1).asInstanceOf[String]))) def write(sig: ScalaSignature, ann: AnnotationNode) =
ann.values.set(1, encode(sig.bytes.arr))
def write(sig: ScalaSignature, ann: AnnotationNode) = ann.values.set(1, encode(sig.bytes.arr)) def ann(cnode: ClassNode): Option[AnnotationNode] =
cnode.visibleAnnotations match {
def ann(cnode: ClassNode): Option[AnnotationNode] = cnode.visibleAnnotations match { case null => None
case null => None case a => a.find(ann => ann.desc.equals("Lscala/reflect/ScalaSignature;"))
case a => a.find(ann => ann.desc.equals("Lscala/reflect/ScalaSignature;"))
} }
} }
@@ -1,21 +1,20 @@
package codechicken.multipart.asm package codechicken.multipart.asm
import java.util.BitSet import java.util.BitSet
trait ScratchBitSet trait ScratchBitSet {
{ private val bitSets = new ThreadLocal[BitSet]
private val bitSets = new ThreadLocal[BitSet]
def getBitSet = bitSets.get match { def getBitSet = bitSets.get match {
case null => case null =>
val bitset = new BitSet val bitset = new BitSet
bitSets.set(bitset) bitSets.set(bitset)
bitset bitset
case bitset => bitset case bitset => bitset
} }
def freshBitSet = { def freshBitSet = {
val bitset = getBitSet val bitset = getBitSet
bitset.clear() bitset.clear()
bitset bitset
} }
} }
@@ -7,294 +7,300 @@ import org.objectweb.asm.Type
import org.objectweb.asm.Type._ import org.objectweb.asm.Type._
import scala.collection.JavaConversions._ import scala.collection.JavaConversions._
object StackAnalyser object StackAnalyser {
{ def width(t: Type): Int = t.getSize
def width(t:Type):Int = t.getSize def width(s: String): Int = width(Type.getType(s))
def width(s:String):Int = width(Type.getType(s)) def width(it: Iterable[Type]): Int = it.foldLeft(0)(_ + width(_))
def width(it:Iterable[Type]):Int = it.foldLeft(0)(_+width(_))
abstract class StackEntry(implicit val insn:AbstractInsnNode) abstract class StackEntry(implicit val insn: AbstractInsnNode) {
{ def getType: Type
def getType:Type }
} abstract class LocalEntry {
abstract class LocalEntry def getType: Type
{ }
def getType:Type
}
case class This(owner:Type) extends LocalEntry case class This(owner: Type) extends LocalEntry {
{ def getType = owner
def getType = owner }
} case class Param(i: Int, t: Type) extends LocalEntry {
case class Param(i:Int, t:Type) extends LocalEntry def getType = t
{ }
def getType = t case class Store(e: StackEntry)(implicit val insn: AbstractInsnNode)
} extends LocalEntry {
case class Store(e:StackEntry)(implicit val insn:AbstractInsnNode) extends LocalEntry def getType = e.getType
{ }
def getType = e.getType
}
case class Const(c:Any)(implicit insn:AbstractInsnNode) extends StackEntry case class Const(c: Any)(implicit insn: AbstractInsnNode) extends StackEntry {
{ def getType = c match {
def getType = c match { case o: Byte => BYTE_TYPE
case o:Byte => BYTE_TYPE case o: Short => SHORT_TYPE
case o:Short => SHORT_TYPE case o: Int => INT_TYPE
case o:Int => INT_TYPE case o: Long => LONG_TYPE
case o:Long => LONG_TYPE case o: Float => FLOAT_TYPE
case o:Float => FLOAT_TYPE case o: Double => DOUBLE_TYPE
case o:Double => DOUBLE_TYPE case o: Char => CHAR_TYPE
case o:Char => CHAR_TYPE case o: Boolean => BOOLEAN_TYPE
case o:Boolean => BOOLEAN_TYPE case o: String => getObjectType("java/lang/String")
case o:String => getObjectType("java/lang/String") case null => getObjectType("java/lang/Object")
case null => getObjectType("java/lang/Object") case _ => throw new IllegalArgumentException("Unknown const " + c)
case _ => throw new IllegalArgumentException("Unknown const "+c)
}
}
case class Load(e:LocalEntry)(implicit insn:AbstractInsnNode) extends StackEntry
{
def getType = e.getType
}
case class UnaryOp(op:Int, e:StackEntry)(implicit insn:AbstractInsnNode) extends StackEntry
{
def getType = e.getType
}
case class BinaryOp(op:Int, e2:StackEntry, e1:StackEntry)(implicit insn:AbstractInsnNode) extends StackEntry
{
def getType = e1.getType
}
case class PrimitiveCast(e:StackEntry, t:Type)(implicit insn:AbstractInsnNode) extends StackEntry
{
def getType = t
}
case class ReturnAddress()(implicit insn:AbstractInsnNode) extends StackEntry
{
def getType = INT_TYPE
}
case class GetField(obj:StackEntry, field:FieldInsnNode)(implicit insn:AbstractInsnNode) extends StackEntry
{
def getType = Type.getType(field.desc)
}
case class Invoke(op:Int, params:Array[StackEntry], obj:StackEntry, method:MethodInsnNode)(implicit insn:AbstractInsnNode) extends StackEntry
{
def getType = Type.getMethodType(method.desc).getReturnType
}
case class New(t:Type)(implicit insn:AbstractInsnNode) extends StackEntry
{
def getType = t
}
case class NewArray(len:StackEntry, t:Type)(implicit insn:AbstractInsnNode) extends StackEntry
{
def getType = t
}
case class ArrayLength(array:StackEntry)(implicit insn:AbstractInsnNode) extends StackEntry
{
def getType = INT_TYPE
}
case class ArrayLoad(index:StackEntry, e:StackEntry)(implicit insn:AbstractInsnNode) extends StackEntry
{
def getType = e.getType.getElementType
}
case class Cast(obj:StackEntry, t:Type)(implicit insn:AbstractInsnNode) extends StackEntry
{
def getType = t
}
case class NewMultiArray(sizes:Array[StackEntry], t:Type)(implicit insn:AbstractInsnNode) extends StackEntry
{
def getType = t
}
case class CaughtException(t:Type)(implicit insn:AbstractInsnNode) extends StackEntry
{
def getType = t
} }
}
case class Load(e: LocalEntry)(implicit insn: AbstractInsnNode)
extends StackEntry {
def getType = e.getType
}
case class UnaryOp(op: Int, e: StackEntry)(implicit insn: AbstractInsnNode)
extends StackEntry {
def getType = e.getType
}
case class BinaryOp(op: Int, e2: StackEntry, e1: StackEntry)(implicit
insn: AbstractInsnNode
) extends StackEntry {
def getType = e1.getType
}
case class PrimitiveCast(e: StackEntry, t: Type)(implicit
insn: AbstractInsnNode
) extends StackEntry {
def getType = t
}
case class ReturnAddress()(implicit insn: AbstractInsnNode)
extends StackEntry {
def getType = INT_TYPE
}
case class GetField(obj: StackEntry, field: FieldInsnNode)(implicit
insn: AbstractInsnNode
) extends StackEntry {
def getType = Type.getType(field.desc)
}
case class Invoke(
op: Int,
params: Array[StackEntry],
obj: StackEntry,
method: MethodInsnNode
)(implicit insn: AbstractInsnNode)
extends StackEntry {
def getType = Type.getMethodType(method.desc).getReturnType
}
case class New(t: Type)(implicit insn: AbstractInsnNode) extends StackEntry {
def getType = t
}
case class NewArray(len: StackEntry, t: Type)(implicit insn: AbstractInsnNode)
extends StackEntry {
def getType = t
}
case class ArrayLength(array: StackEntry)(implicit insn: AbstractInsnNode)
extends StackEntry {
def getType = INT_TYPE
}
case class ArrayLoad(index: StackEntry, e: StackEntry)(implicit
insn: AbstractInsnNode
) extends StackEntry {
def getType = e.getType.getElementType
}
case class Cast(obj: StackEntry, t: Type)(implicit insn: AbstractInsnNode)
extends StackEntry {
def getType = t
}
case class NewMultiArray(sizes: Array[StackEntry], t: Type)(implicit
insn: AbstractInsnNode
) extends StackEntry {
def getType = t
}
case class CaughtException(t: Type)(implicit insn: AbstractInsnNode)
extends StackEntry {
def getType = t
}
} }
class StackAnalyser(val owner:Type, val m:MethodNode) class StackAnalyser(val owner: Type, val m: MethodNode) {
{ import StackAnalyser._
import StackAnalyser._
val stack = MList[StackEntry]() val stack = MList[StackEntry]()
val locals = MList[LocalEntry]() val locals = MList[LocalEntry]()
private val catchHandlers = MMap[LabelNode, TryCatchBlockNode]() private val catchHandlers = MMap[LabelNode, TryCatchBlockNode]()
{ {
if((m.access & ACC_STATIC) == 0) if ((m.access & ACC_STATIC) == 0)
pushL(This(owner)) pushL(This(owner))
val ptypes = getArgumentTypes(m.desc) val ptypes = getArgumentTypes(m.desc)
for(i <- 0 until ptypes.length) for (i <- 0 until ptypes.length)
pushL(Param(i, ptypes(i))) pushL(Param(i, ptypes(i)))
m.tryCatchBlocks.foreach(b => catchHandlers.put(b.handler, b)) m.tryCatchBlocks.foreach(b => catchHandlers.put(b.handler, b))
}
def pushL(entry: LocalEntry) = setL(locals.size, entry)
def setL(i: Int, entry: LocalEntry) = {
while (i + entry.getType.getSize > locals.size) locals += null
locals(i) = entry
if (entry.getType.getSize == 2)
locals(i + 1) = entry
}
def push(entry: StackEntry) = insert(0, entry)
def _pop(i: Int = 0) = stack.remove(stack.size - i - 1)
def pop(i: Int = 0) = {
val e = _pop(i)
if (e.getType.getSize == 2) {
if (peek(i) != e)
throw new IllegalStateException(
"Wide stack entry elems don't match (" + e + "," + peek(i)
)
_pop(i)
} }
e
}
def pushL(entry:LocalEntry) = setL(locals.size, entry) def peek(i: Int = 0) = stack(stack.size - i - 1)
def setL(i:Int, entry:LocalEntry) = def insert(i: Int, entry: StackEntry) {
{ if (entry.getType.getSize == 0)
while(i+entry.getType.getSize > locals.size) locals += null return
locals(i) = entry stack.insert(stack.size - i, entry)
if(entry.getType.getSize == 2) if (entry.getType.getSize == 2)
locals(i+1) = entry stack.insert(stack.size - i, entry)
} }
def push(entry:StackEntry) = insert(0, entry) def popArgs(desc: String) = {
val t = getType(desc)
val args = new Array[StackEntry](t.getArgumentTypes.length)
for (i <- 0 until args.length)
args(args.length - i - 1) = pop()
args
}
def _pop(i:Int = 0) = stack.remove(stack.size-i-1) def visitInsn(ainsn: AbstractInsnNode) {
implicit val thisInsn = ainsn // passes to any StackEntry we create
ainsn match {
case insn: InsnNode =>
ainsn.getOpcode match {
case ACONST_NULL => push(Const(null))
case ICONST_M1 => push(Const(-1))
case ICONST_0 => push(Const(0))
case ICONST_1 => push(Const(1))
case ICONST_2 => push(Const(2))
case ICONST_3 => push(Const(3))
case ICONST_4 => push(Const(4))
case ICONST_5 => push(Const(5))
case LCONST_0 => push(Const(0L))
case LCONST_1 => push(Const(1L))
case FCONST_0 => push(Const(0f))
case FCONST_1 => push(Const(1f))
case FCONST_2 => push(Const(2f))
case DCONST_0 => push(Const(0d))
case DCONST_1 => push(Const(1d))
case i if i >= IALOAD && i <= SALOAD =>
push(ArrayLoad(pop(), pop()))
case i if i >= IASTORE && i <= SASTORE =>
pop(); pop(); pop()
case POP => _pop()
case POP2 => _pop(); _pop()
case DUP => push(peek())
case DUP_X1 => insert(2, peek())
case DUP_X2 => insert(3, peek())
case DUP2 => push(peek(1)); push(peek(1))
case DUP2_X1 => insert(3, peek(1)); insert(3, peek())
case DUP2_X2 => insert(4, peek(1)); insert(4, peek())
case SWAP => push(pop(1))
case i if i >= IADD && i <= DREM =>
push(BinaryOp(i, pop(), pop()))
case i if i >= INEG && i <= DNEG =>
push(UnaryOp(i, pop()))
case i if i >= ISHL && i <= LXOR =>
push(BinaryOp(i, pop(), pop()))
case L2I | F2I | D2I => push(PrimitiveCast(pop(), DOUBLE_TYPE))
case I2L | F2L | D2L => push(PrimitiveCast(pop(), LONG_TYPE))
case I2F | L2F | D2F => push(PrimitiveCast(pop(), FLOAT_TYPE))
case I2D | L2D | F2D => push(PrimitiveCast(pop(), DOUBLE_TYPE))
case I2B => push(PrimitiveCast(pop(), BYTE_TYPE))
case I2C => push(PrimitiveCast(pop(), CHAR_TYPE))
case I2S => push(PrimitiveCast(pop(), SHORT_TYPE))
case i if i >= LCMP && i <= DCMPG =>
push(BinaryOp(i, pop(), pop()))
case i if i >= IRETURN && i <= ARETURN => pop()
case ARRAYLENGTH => push(ArrayLength(pop()))
case ATHROW => pop()
case MONITORENTER | MONITOREXIT => pop()
case _ =>
def pop(i:Int = 0) =
{
val e = _pop(i)
if(e.getType.getSize == 2)
{
if(peek(i) != e) throw new IllegalStateException("Wide stack entry elems don't match ("+e+","+peek(i))
_pop(i)
} }
e case iinsn: IntInsnNode =>
} ainsn.getOpcode match {
case BIPUSH => push(Const(iinsn.operand.toByte))
def peek(i:Int = 0) = stack(stack.size-i-1) case SIPUSH => push(Const(iinsn.operand.toShort))
}
def insert(i:Int, entry:StackEntry) case ldcinsn: LdcInsnNode =>
{ ainsn.getOpcode match {
if(entry.getType.getSize == 0) case LDC => push(Const(ldcinsn.cst))
return }
stack.insert(stack.size-i, entry) case vinsn: VarInsnNode =>
if(entry.getType.getSize == 2) ainsn.getOpcode match {
stack.insert(stack.size-i, entry) case i if i >= ILOAD && i <= ALOAD =>
} push(Load(locals(vinsn.`var`)))
case i if i >= ISTORE && i <= ASTORE =>
def popArgs(desc:String) = setL(vinsn.`var`, Store(pop()))
{ }
val t = getType(desc) case incinsn: IincInsnNode =>
val args = new Array[StackEntry](t.getArgumentTypes.length) ainsn.getOpcode match {
for(i <- 0 until args.length) case IINC =>
args(args.length-i-1) = pop() setL(
args incinsn.`var`,
} Store(
BinaryOp(IINC, Const(incinsn.incr), Load(locals(incinsn.`var`)))
def visitInsn(ainsn:AbstractInsnNode) )
{ )
implicit val thisInsn = ainsn//passes to any StackEntry we create }
ainsn match { case jinsn: JumpInsnNode =>
case insn:InsnNode => ainsn.getOpcode match ainsn.getOpcode match {
{ case i if i >= IFEQ && i <= IFLE => pop()
case ACONST_NULL => push(Const(null)) case i if i >= IF_ICMPEQ && i <= IF_ACMPNE => pop(); pop()
case ICONST_M1 => push(Const(-1)) case JSR => push(ReturnAddress())
case ICONST_0 => push(Const(0)) case IFNULL | IFNONNULL => pop()
case ICONST_1 => push(Const(1)) case GOTO =>
case ICONST_2 => push(Const(2)) }
case ICONST_3 => push(Const(3)) case sinsn: TableSwitchInsnNode => pop()
case ICONST_4 => push(Const(4)) case linsn: LookupSwitchInsnNode => pop()
case ICONST_5 => push(Const(5)) case finsn: FieldInsnNode =>
case LCONST_0 => push(Const(0L)) ainsn.getOpcode match {
case LCONST_1 => push(Const(1L)) case GETSTATIC => push(GetField(null, finsn))
case FCONST_0 => push(Const(0F)) case PUTSTATIC => pop()
case FCONST_1 => push(Const(1F)) case GETFIELD => push(GetField(pop(), finsn))
case FCONST_2 => push(Const(2F)) case PUTFIELD => pop(); pop()
case DCONST_0 => push(Const(0D)) }
case DCONST_1 => push(Const(1D)) case minsn: MethodInsnNode =>
ainsn.getOpcode match {
case i if i >= IALOAD && i <= SALOAD => case INVOKEVIRTUAL | INVOKESPECIAL | INVOKEINTERFACE =>
push(ArrayLoad(pop(), pop())) push(Invoke(ainsn.getOpcode, popArgs(minsn.desc), pop(), minsn))
case i if i >= IASTORE && i <= SASTORE => case INVOKESTATIC =>
pop(); pop(); pop() push(Invoke(ainsn.getOpcode, popArgs(minsn.desc), null, minsn))
}
case POP => _pop() case tinsn: TypeInsnNode =>
case POP2 => _pop(); _pop() ainsn.getOpcode match {
case DUP => push(peek()) case NEW => push(New(getObjectType(tinsn.desc)))
case DUP_X1 => insert(2, peek()) case NEWARRAY => push(NewArray(pop(), getObjectType(tinsn.desc)))
case DUP_X2 => insert(3, peek()) case ANEWARRAY =>
case DUP2 => push(peek(1)); push(peek(1)) push(NewArray(pop(), getObjectType("[" + tinsn.desc)))
case DUP2_X1 => insert(3, peek(1)); insert(3, peek()) case CHECKCAST => push(Cast(pop(), getObjectType(tinsn.desc)))
case DUP2_X2 => insert(4, peek(1)); insert(4, peek()) case INSTANCEOF => push(UnaryOp(INSTANCEOF, pop()))
case SWAP => push(pop(1)) }
case mainsn: MultiANewArrayInsnNode =>
case i if i >= IADD && i <= DREM => val sizes = new Array[StackEntry](mainsn.dims)
push(BinaryOp(i, pop(), pop())) for (i <- 0 until sizes.length)
case i if i >= INEG && i <= DNEG => sizes(i) = pop()
push(UnaryOp(i, pop())) push(NewMultiArray(sizes, getType(mainsn.desc)))
case i if i >= ISHL && i <= LXOR => /*case fnode:FrameNode => fnode.`type` match
push(BinaryOp(i, pop(), pop()))
case L2I|F2I|D2I => push(PrimitiveCast(pop(), DOUBLE_TYPE))
case I2L|F2L|D2L => push(PrimitiveCast(pop(), LONG_TYPE))
case I2F|L2F|D2F => push(PrimitiveCast(pop(), FLOAT_TYPE))
case I2D|L2D|F2D => push(PrimitiveCast(pop(), DOUBLE_TYPE))
case I2B => push(PrimitiveCast(pop(), BYTE_TYPE))
case I2C => push(PrimitiveCast(pop(), CHAR_TYPE))
case I2S => push(PrimitiveCast(pop(), SHORT_TYPE))
case i if i >= LCMP && i <= DCMPG =>
push(BinaryOp(i, pop(), pop()))
case i if i >= IRETURN && i <= ARETURN => pop()
case ARRAYLENGTH => push(ArrayLength(pop()))
case ATHROW => pop()
case MONITORENTER|MONITOREXIT => pop()
case _ =>
}
case iinsn:IntInsnNode => ainsn.getOpcode match
{
case BIPUSH => push(Const(iinsn.operand.toByte))
case SIPUSH => push(Const(iinsn.operand.toShort))
}
case ldcinsn:LdcInsnNode => ainsn.getOpcode match
{
case LDC => push(Const(ldcinsn.cst))
}
case vinsn:VarInsnNode => ainsn.getOpcode match
{
case i if i >= ILOAD && i <= ALOAD =>
push(Load(locals(vinsn.`var`)))
case i if i >= ISTORE && i <= ASTORE =>
setL(vinsn.`var`, Store(pop()))
}
case incinsn:IincInsnNode => ainsn.getOpcode match
{
case IINC => setL(incinsn.`var`, Store(BinaryOp(IINC, Const(incinsn.incr), Load(locals(incinsn.`var`)))))
}
case jinsn:JumpInsnNode => ainsn.getOpcode match
{
case i if i >= IFEQ && i <= IFLE => pop()
case i if i >= IF_ICMPEQ && i <= IF_ACMPNE => pop(); pop()
case JSR => push(ReturnAddress())
case IFNULL|IFNONNULL => pop()
case GOTO =>
}
case sinsn:TableSwitchInsnNode => pop()
case linsn:LookupSwitchInsnNode => pop()
case finsn:FieldInsnNode => ainsn.getOpcode match
{
case GETSTATIC => push(GetField(null, finsn))
case PUTSTATIC => pop()
case GETFIELD => push(GetField(pop(), finsn))
case PUTFIELD => pop(); pop()
}
case minsn:MethodInsnNode => ainsn.getOpcode match
{
case INVOKEVIRTUAL|INVOKESPECIAL|INVOKEINTERFACE =>
push(Invoke(ainsn.getOpcode, popArgs(minsn.desc), pop(), minsn))
case INVOKESTATIC =>
push(Invoke(ainsn.getOpcode, popArgs(minsn.desc), null, minsn))
}
case tinsn:TypeInsnNode => ainsn.getOpcode match
{
case NEW => push(New(getType(tinsn.desc)))
case NEWARRAY => push(NewArray(pop(), getType(tinsn.desc)))
case ANEWARRAY => push(NewArray(pop(), getType("["+tinsn.desc)))
case CHECKCAST => push(Cast(pop(), getType(tinsn.desc)))
case INSTANCEOF => push(UnaryOp(INSTANCEOF, pop()))
}
case mainsn:MultiANewArrayInsnNode =>
val sizes = new Array[StackEntry](mainsn.dims)
for(i <- 0 until sizes.length)
sizes(i) = pop()
push(NewMultiArray(sizes, getType(mainsn.desc)))
/*case fnode:FrameNode => fnode.`type` match
{ {
case F_NEW|F_FULL => println("reset stacks/locals") case F_NEW|F_FULL => println("reset stacks/locals")
case F_APPEND => println("add local") case F_APPEND => println("add local")
@@ -302,13 +308,13 @@ class StackAnalyser(val owner:Type, val m:MethodNode)
case F_SAME => println("reset") case F_SAME => println("reset")
case F_SAME1 => println("reset locals and all but bottom stack") case F_SAME1 => println("reset locals and all but bottom stack")
}*/ }*/
case lnode:LabelNode => case lnode: LabelNode =>
catchHandlers.get(lnode) match catchHandlers.get(lnode) match {
{ case Some(tcblock) =>
case Some(tcblock) => push(CaughtException(Type.getType(tcblock.`type`))) push(CaughtException(Type.getType(tcblock.`type`)))
case None => case None =>
}
case _ =>
} }
case _ =>
} }
}
} }
Loaded 100 of 131 files, more files were not shown because too many files have changed in this diff. Show more