diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..315b30a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,8 @@ +root = true + +[*] +charset = utf-8 +indent_size = 4 +indent_style = space +insert_final_newline = true +max_line_length = off diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 936d3f7..40f0530 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,7 +12,7 @@ jobs: strategy: matrix: javaVersion: ["17"] - mcVersion: ['1.16.5'] + mcVersion: ['1.20.2'] name: Minecraft ${{ matrix.mcVersion }} with Java v${{ matrix.javaVersion }} steps: - uses: actions/checkout@v3 diff --git a/.github/workflows/gradle-wrapper-validation.yml b/.github/workflows/gradle-wrapper-validation.yml new file mode 100644 index 0000000..3bbd624 --- /dev/null +++ b/.github/workflows/gradle-wrapper-validation.yml @@ -0,0 +1,13 @@ +name: "Validate Gradle Wrapper" +on: [push, pull_request] + +jobs: + validation: + # Only run on PRs if the source branch is on someone else's repo + if: "${{ github.event_name != 'pull_request' || github.repository != github.event.pull_request.head.repo.full_name }}" + + name: "Validation" + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: gradle/wrapper-validation-action@v1 diff --git a/.gitignore b/.gitignore index ba7ff76..e94b7f2 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,6 @@ node_modules/ # Project output gradle.properties block_collision_shapes*.json -output/ \ No newline at end of file +output/ +.idea/ +*.iml diff --git a/README.md b/README.md index b1fb944..d79c1c0 100644 --- a/README.md +++ b/README.md @@ -8,5 +8,5 @@ Extract block collision shapes and attributes from Minecraft using Fabric mod lo ## Usage Open the repo [here](https://gitpod.io/#https://github.com/PrismarineJS/McDataExtracting) -then, run `npm run start -- 1.16.5` in the shell (replace 1.16.5 with the version you want) -then, run `gradle run` +then, run `npm run start -- 1.20.2` in the shell (replace 1.20.2 with the version you want) +then, run `./gradlew run` diff --git a/build-properties.js b/build-properties.js index 3c9bad9..96a4397 100644 --- a/build-properties.js +++ b/build-properties.js @@ -13,7 +13,7 @@ async function start () { const [,, wantedVersion] = process.argv const yarnMappingsVersion = await getYarnMappingsVersion(wantedVersion) const fabricLoomVersion = await getFabricLoomVersion() - const text = `minecraft_version=${wantedVersion}\nyarn_mappings=${yarnMappingsVersion}\nfabric_loom_version=${fabricLoomVersion}` + const text = `minecraft_version=${wantedVersion}\nyarn_mappings=${yarnMappingsVersion}\nfabric_loom_version=${fabricLoomVersion}\norg.gradle.jvmargs=-Xmx4G -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8` await fs.writeFile('gradle.properties', text) console.info('Config file written.') } @@ -31,7 +31,7 @@ async function getYarnMappingsVersion (wantedVersion) { async function getFabricLoomVersion () { const xmlData = (await (await fetch('https://maven.fabricmc.net/net/fabricmc/fabric-loom/maven-metadata.xml')).text()) - return parser.parse(xmlData).metadata.versioning.release + return new parser.XMLParser().parse(xmlData).metadata.versioning.release } start() diff --git a/build.gradle b/build.gradle index 87bee04..8e76d75 100644 --- a/build.gradle +++ b/build.gradle @@ -1,15 +1,14 @@ buildscript { - repositories { - jcenter() - maven { - name = 'Fabric' - url = 'https://maven.fabricmc.net/' - } - gradlePluginPortal() - } - dependencies { - classpath "net.fabricmc:fabric-loom:${project.fabric_loom_version}" - } + repositories { + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + gradlePluginPortal() + } + dependencies { + classpath "net.fabricmc:fabric-loom:${project.fabric_loom_version}" + } } apply plugin: 'fabric-loom' @@ -18,21 +17,21 @@ apply plugin: 'application' group 'mcextract' version '0.1.1-SNAPSHOT' -sourceCompatibility = 1.8 +sourceCompatibility = 17 +targetCompatibility = 17 repositories { - mavenCentral() + mavenCentral() } dependencies { - //to change the versions see the gradle.properties file - minecraft "com.mojang:minecraft:${project.minecraft_version}" - // mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" - mappings loom.officialMojangMappings() - modImplementation "net.fabricmc:fabric-loader" - modImplementation "net.fabricmc.fabric-api:fabric-api:0.30.0+1.16" + // To change the versions see the gradle.properties file + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings loom.officialMojangMappings() + modImplementation "net.fabricmc:fabric-loader" + modImplementation "net.fabricmc.fabric-api:fabric-api:0.30.0+1.16" } application { - mainClassName = "mcextract.Main" + mainClassName = "mcextract.Main" } diff --git a/gradle.properties.example b/gradle.properties.example index 9bd0925..96c6042 100644 --- a/gradle.properties.example +++ b/gradle.properties.example @@ -1,3 +1,4 @@ minecraft_version=1.16.5 yarn_mappings=1.16.5+build.4 fabric-loom_version=0.8 +org.gradle.jvmargs=-Xmx4G -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7f93135 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ac72c34 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..0adc8e1 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# 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/HEAD/subprojects/plugins/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 + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + 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 +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # 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 + + +# 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 $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# 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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +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. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/package-lock.json b/package-lock.json index 5cd8aec..c03ffa8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,23 +9,29 @@ "version": "1.0.0", "license": "ISC", "dependencies": { - "fast-xml-parser": "^3.19.0", + "fast-xml-parser": "^4.2.3", "node-fetch": "^2.6.1" } }, "node_modules/fast-xml-parser": { - "version": "3.21.1", - "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-3.21.1.tgz", - "integrity": "sha512-FTFVjYoBOZTJekiUsawGsSYV9QL0A+zDYCRj7y34IO6Jg+2IMYEtQa+bbictpdpV8dHxXywqU7C0gRDEOFtBFg==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.3.2.tgz", + "integrity": "sha512-rmrXUXwbJedoXkStenj1kkljNF7ugn5ZjR9FJcwmCfcCbtOMDghPajbc+Tck6vE6F5XsDmx+Pr2le9fw8+pXBg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + }, + { + "type": "paypal", + "url": "https://paypal.me/naturalintelligence" + } + ], "dependencies": { - "strnum": "^1.0.4" + "strnum": "^1.0.5" }, "bin": { - "xml2js": "cli.js" - }, - "funding": { - "type": "paypal", - "url": "https://paypal.me/naturalintelligence" + "fxparser": "src/cli/cli.js" } }, "node_modules/node-fetch": { @@ -74,11 +80,11 @@ }, "dependencies": { "fast-xml-parser": { - "version": "3.21.1", - "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-3.21.1.tgz", - "integrity": "sha512-FTFVjYoBOZTJekiUsawGsSYV9QL0A+zDYCRj7y34IO6Jg+2IMYEtQa+bbictpdpV8dHxXywqU7C0gRDEOFtBFg==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.3.2.tgz", + "integrity": "sha512-rmrXUXwbJedoXkStenj1kkljNF7ugn5ZjR9FJcwmCfcCbtOMDghPajbc+Tck6vE6F5XsDmx+Pr2le9fw8+pXBg==", "requires": { - "strnum": "^1.0.4" + "strnum": "^1.0.5" } }, "node-fetch": { diff --git a/package.json b/package.json index 63dc680..81ee599 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "author": "", "license": "ISC", "dependencies": { - "fast-xml-parser": "^3.19.0", + "fast-xml-parser": "^4.2.3", "node-fetch": "^2.6.1" } } diff --git a/src/main/java/mcextract/BlockCollisionBoxStorage.java b/src/main/java/mcextract/BlockCollisionBoxStorage.java index b060020..e930cec 100644 --- a/src/main/java/mcextract/BlockCollisionBoxStorage.java +++ b/src/main/java/mcextract/BlockCollisionBoxStorage.java @@ -1,89 +1,79 @@ package mcextract; -import com.google.gson.*; +import com.google.gson.JsonObject; import net.minecraft.world.phys.AABB; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; public class BlockCollisionBoxStorage { - private final HashMap blocks = new HashMap<>(); + private final Map blocks = new HashMap<>(); - public BlockCollisionBoxStorage(JsonObject jsonRoot) { - final HashMap shapes = new HashMap<>(); - for (Map.Entry shapeEntry : jsonRoot.getAsJsonObject("shapes").entrySet()) { - final JsonArray boxesJson = shapeEntry.getValue().getAsJsonArray(); - final ArrayList boxes = new ArrayList<>(boxesJson.size()); - for (JsonElement element : boxesJson) { - final JsonArray a = element.getAsJsonArray(); - int i = 0; - boxes.add(new AABB( - a.get(i++).getAsDouble(), - a.get(i++).getAsDouble(), - a.get(i++).getAsDouble(), - a.get(i++).getAsDouble(), - a.get(i++).getAsDouble(), - a.get(i++).getAsDouble())); - } - shapes.put(Integer.parseInt(shapeEntry.getKey()), new Shape(boxes)); - } + public BlockCollisionBoxStorage(JsonObject jsonRoot) { + var shapes = new HashMap(); + for (var shapeEntry : jsonRoot.getAsJsonObject("shapes").entrySet()) { + var boxesJson = shapeEntry.getValue().getAsJsonArray(); + var boxes = new ArrayList(boxesJson.size()); + for (var element : boxesJson) { + var elementArray = element.getAsJsonArray(); + boxes.add(new AABB( + elementArray.get(0).getAsDouble(), + elementArray.get(1).getAsDouble(), + elementArray.get(2).getAsDouble(), + elementArray.get(3).getAsDouble(), + elementArray.get(4).getAsDouble(), + elementArray.get(5).getAsDouble() + )); + } + shapes.put(Integer.parseInt(shapeEntry.getKey()), new Shape(boxes)); + } - for (Map.Entry blockEntry : jsonRoot.getAsJsonObject("blocks").entrySet()) { - final JsonElement value = blockEntry.getValue(); - if (value == null) { - blocks.put(blockEntry.getKey(), new SameShapePerBlockState(Shape.EMPTY)); - } else if (value.isJsonPrimitive()) { - final Shape shape = shapes.get(value.getAsInt()); - blocks.put(blockEntry.getKey(), new SameShapePerBlockState(shape)); - } else { - final JsonArray shapeIds = value.getAsJsonArray(); - final Shape[] blockStatesShapes = new Shape[shapeIds.size()]; - for (int i = 0; i < blockStatesShapes.length; i++) { - blockStatesShapes[i] = shapes.get(shapeIds.get(i).getAsInt()); - } - blocks.put(blockEntry.getKey(), new OneShapePerBlockState(blockStatesShapes)); - } - } - } + for (var blockEntry : jsonRoot.getAsJsonObject("blocks").entrySet()) { + var value = blockEntry.getValue(); + if (value == null) { + blocks.put(blockEntry.getKey(), new SameShapePerBlockState(Shape.EMPTY)); + } else if (value.isJsonPrimitive()) { + var shape = shapes.get(value.getAsInt()); + blocks.put(blockEntry.getKey(), new SameShapePerBlockState(shape)); + } else { + var shapeIds = value.getAsJsonArray(); + var blockStatesShapes = new Shape[shapeIds.size()]; + for (int i = 0; i < blockStatesShapes.length; i++) { + blockStatesShapes[i] = shapes.get(shapeIds.get(i).getAsInt()); + } + blocks.put(blockEntry.getKey(), new OneShapePerBlockState(blockStatesShapes)); + } + } + } - public Shape getBlockShape(String blockId, int blockStateId) { - final ShapePerBlockState blockStatesShapeIds = blocks.get(blockId); - if (blockStatesShapeIds == null) return null; // unknown block - return blockStatesShapeIds.getShapeIdForBlockState(blockStateId); - } + public Shape getBlockShape(String blockId, int blockStateId) { + final ShapePerBlockState blockStatesShapeIds = blocks.get(blockId); + if (blockStatesShapeIds == null) return null; // unknown block + return blockStatesShapeIds.getShapeIdForBlockState(blockStateId); + } - private interface ShapePerBlockState { - Shape getShapeIdForBlockState(int blockStateId); - } + private interface ShapePerBlockState { + Shape getShapeIdForBlockState(int blockStateId); + } - private static class SameShapePerBlockState implements ShapePerBlockState { - private final Shape shape; + private record SameShapePerBlockState(Shape shape) implements ShapePerBlockState { + @Override + public Shape getShapeIdForBlockState(int blockStateId) { + return shape; + } + } - private SameShapePerBlockState(Shape shape) { - this.shape = shape; - } - - @Override - public Shape getShapeIdForBlockState(int blockStateId) { - return shape; - } - } - - private static class OneShapePerBlockState implements ShapePerBlockState { - private final Shape[] shapes; - - private OneShapePerBlockState(Shape[] shapes) { - this.shapes = shapes; - } - - @Override - public Shape getShapeIdForBlockState(int blockStateId) { - if (blockStateId < 0) throw new IllegalArgumentException("block state id < 0"); - if (blockStateId >= shapes.length) { - throw new IllegalArgumentException("block state id " + blockStateId - + " out of bounds for length " + shapes.length); - } - if (shapes[blockStateId] == null) return Shape.EMPTY; - return shapes[blockStateId]; - } - } + private record OneShapePerBlockState(Shape[] shapes) implements ShapePerBlockState { + @Override + public Shape getShapeIdForBlockState(int blockStateId) { + if (blockStateId < 0) throw new IllegalArgumentException("block state id < 0"); + if (blockStateId >= shapes.length) { + throw new IllegalArgumentException("block state id " + blockStateId + + " out of bounds for length " + shapes.length); + } + if (shapes[blockStateId] == null) return Shape.EMPTY; + return shapes[blockStateId]; + } + } } diff --git a/src/main/java/mcextract/Main.java b/src/main/java/mcextract/Main.java index f3796d6..18a4601 100644 --- a/src/main/java/mcextract/Main.java +++ b/src/main/java/mcextract/Main.java @@ -1,258 +1,325 @@ package mcextract; -import com.google.common.collect.ImmutableList; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonObject; -import net.minecraft.server.Bootstrap; import net.minecraft.SharedConstants; +import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.server.Bootstrap; +import net.minecraft.world.entity.ai.attributes.RangedAttribute; +import net.minecraft.world.level.EmptyBlockGetter; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.FallingBlock; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.core.Registry; -import net.minecraft.world.entity.ai.attributes.Attribute; -import net.minecraft.world.entity.ai.attributes.RangedAttribute; -import net.minecraft.resources.ResourceLocation; import java.io.IOException; +import java.lang.reflect.Field; import java.nio.file.Files; +import java.nio.file.Path; import java.nio.file.Paths; -import java.time.LocalDateTime; import java.util.*; -import static java.nio.charset.StandardCharsets.UTF_8; -import static java.time.format.DateTimeFormatter.ISO_DATE_TIME; - -import java.lang.reflect.Field; - public class Main { - public static String getGameVersion() { - return SharedConstants.getCurrentVersion().getName(); - // return SharedConstants.VERSION_STRING; - } - - public static String getArg(String[] args, String argName, String defaultValue) { - for (int i = 0; i < args.length; i++) { - if (args[i].equals(argName)) { - return args[i + 1]; - } - } - return defaultValue; - } - - // Static method to get a private field from a class - public static T getPrivateValue(Class classToAccess, E instance, String fieldName) { - try { - Field field = classToAccess.getDeclaredField(fieldName); - field.setAccessible(true); - return (T) field.get(instance); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public static void main(String[] args) { - final boolean write = true; - - final String mcVersion = getGameVersion(); - System.err.println("Initializing Minecraft " + mcVersion + " registries ..."); - Bootstrap.bootStrap(); - System.err.println("Done."); - - // Get --outputDir from args - String outputDir = getArg(args, "--outputDir", ""); - if (outputDir.length() > 0 && !outputDir.endsWith("/")) { - outputDir += "/"; - } - // make the output directory if it doesn't exist - try { - Files.createDirectories(Paths.get(outputDir)); - } catch (IOException e) { - e.printStackTrace(); - System.err.println("Failed to create output directory."); - } - System.err.println("Extraction output directory: " + outputDir); - - JsonObject allBlocksJson = doBlockShapeExtraction(); - JsonObject allAttributesJson = doAttributeExtraction(); - - if (write) { - // Block shapes - try { - writeBlockShapes(outputDir, allBlocksJson); - System.err.println("Done with block shapes."); - } catch (IOException e) { - e.printStackTrace(); - System.err.println("Failed to write block shapes."); - } - - // Attributes - try { - writeAttributes(outputDir, allAttributesJson); - System.err.println("Done with attributes."); - } catch (IOException e) { - e.printStackTrace(); - System.err.println("Failed to write attributes."); - } - } - - System.err.println("Running collision sanity checks ..."); - final ArrayList failures = runSanityChecks(new BlockCollisionBoxStorage(allBlocksJson)); - System.err.println(failures.size() + " failures."); - } - - public static JsonObject doBlockShapeExtraction() { - System.err.println("Extracting Block data ..."); - final JsonObject allBlocksJson = extractBlockCollisionShapes(); - System.err.println("Extracted data for " + allBlocksJson.getAsJsonObject("blocks").size() + " blocks" - + " and " + allBlocksJson.getAsJsonObject("shapes").size() + " distinct shapes."); - return allBlocksJson; - } - - public static void writeBlockShapes(String outputDir, JsonObject allBlocksJson) throws IOException { - String outString = allBlocksJson.toString(); - outString = outString.replaceAll("\\},|null,|\"[_a-zA-Z]+\":[0-9]+,", "$0\n"); - outString = outString.replaceAll("\\],\"", "],\n\""); - - String nowIso = ISO_DATE_TIME.format(LocalDateTime.now()); - String outPath = outputDir + "blockCollisionShapes.json"; - System.err.println("Writing block shapes to '" + outPath + "'..."); - Files.write(Paths.get(outPath), outString.getBytes(UTF_8)); - } - - public static JsonObject doAttributeExtraction() { - System.err.println("Extracting Attribute data ..."); - final JsonObject allAttributesJson = extractAttributes(); - System.err.println("Extracted data for " + allAttributesJson.size() + " attributes."); - return allAttributesJson; - } - - public static void writeAttributes(String outputDir, JsonObject allAttributesJson) throws IOException { - // Pretty pritned JSON - String outString = allAttributesJson.toString(); - outString = outString.replaceAll("\\},|null,|\"[_a-zA-Z]+\":[0-9]+,", "$0\n"); - String nowIso = ISO_DATE_TIME.format(LocalDateTime.now()); - String outPath = outputDir + "attributes.json"; - System.err.println("Writing attributes to '" + outPath + "'..."); - Files.write(Paths.get(outPath), outString.getBytes(UTF_8)); - } - - // COLLISIONS - - /** - * output data structure: - *
-	 * {
-	 *   "shapes": { [shape]: [[x1,y1,z1, x2,y2,z2], ...] },
-	 *   "blocks": {
-	 *     [block]: shape, // all block states have same shape
-	 *     [block]: [ shape, ... ], // at least one state shape different from others; indexed by stateId
-	 *     ...
-	 *   }
-	 * }
-	 * 
- */ - private static JsonObject extractBlockCollisionShapes() { - final JsonObject allBlocksJson = new JsonObject(); - final HashMap shapeIds = new HashMap<>(); - - for (final Block block : Registry.BLOCK) { - final ImmutableList states = block.getStateDefinition().getPossibleStates(); - final int[] boxesByState = new int[states.size()]; - - final Shape state0Shape = new Shape(block.defaultBlockState()); - final Integer state0ShapeId = lookupAndPersistShapeId(state0Shape, shapeIds); - boolean allSame = true; - - for (int stateId = 0; stateId < states.size(); stateId++) { - BlockState blockState = states.get(stateId); - - final Shape stateShape = new Shape(blockState); - final Integer stateShapeId = lookupAndPersistShapeId(stateShape, shapeIds); - boxesByState[stateId] = stateShapeId; - - if (allSame && !Objects.equals(state0ShapeId, stateShapeId)) { - allSame = false; - } - } - - final String blockId = getBlockIdString(block); - if (allSame) { - allBlocksJson.addProperty(blockId, state0ShapeId); - } else { - final JsonArray blockJson = new JsonArray(); - for (int shapeId : boxesByState) { - blockJson.add(shapeId); - } - allBlocksJson.add(blockId, blockJson); - - System.err.println(blockId + ": " + boxesByState.length + " states, " - + (boxesByState.length - blockJson.size()) + " empty"); - } - } - - final JsonObject allShapesJson = new JsonObject(); - shapeIds.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue)) - .forEach(entry -> allShapesJson.add(entry.getValue().toString(), entry.getKey().toJson())); - - final JsonObject rootJson = new JsonObject(); - rootJson.add("blocks", allBlocksJson); - rootJson.add("shapes", allShapesJson); - return rootJson; - } - - private static ArrayList runSanityChecks(BlockCollisionBoxStorage storage) { - final ArrayList failures = new ArrayList<>(); - for (final Block block : Registry.BLOCK) { - final String blockId = getBlockIdString(block); - final ImmutableList states = block.getStateDefinition().getPossibleStates(); - for (int stateId = 0; stateId < states.size(); stateId++) { - BlockState blockState = states.get(stateId); - - final Shape mcShape = new Shape(blockState); - - final Shape storageShape = storage.getBlockShape(blockId, stateId); - - if (!mcShape.equals(storageShape)) { - System.err.println("ERROR: shapes differ: block=" + blockId + " state=" + stateId); - failures.add(blockId + ":" + stateId); - } - } - } - return failures; - } - - private static Integer lookupAndPersistShapeId(Shape shape, HashMap shapeIds) { - return shapeIds.computeIfAbsent(shape, s -> shapeIds.size()); - } - - private static String getBlockIdString(Block block) { - final String blockId = Integer.toString(Registry.BLOCK.getId(block)); - if (!blockId.startsWith("minecraft:")) return blockId; - return blockId.replaceAll("^minecraft:", ""); - } - - // ATTRIBUTES - public static JsonObject extractAttributes() { - final JsonObject allAttributes = new JsonObject(); - for (Attribute attr : Registry.ATTRIBUTE) { - final JsonObject attrJson = new JsonObject(); - attrJson.addProperty("default", attr.getDefaultValue()); - if (attr instanceof RangedAttribute) { - final RangedAttribute rangedAttr = (RangedAttribute) attr; - double minVal = getPrivateValue(RangedAttribute.class, rangedAttr, "minValue"); - double maxVal = getPrivateValue(RangedAttribute.class, rangedAttr, "maxValue"); - attrJson.addProperty("min", minVal); - attrJson.addProperty("max", maxVal); - } - - ResourceLocation key = Registry.ATTRIBUTE.getKey(attr); - if (key == null) { - System.err.println("ERROR: attribute has no key: " + attr); - continue; - } - attrJson.addProperty("description", attr.getDescriptionId()); - attrJson.addProperty("id", Registry.ATTRIBUTE.getId(attr)); - allAttributes.add(key.toString(), attrJson); - } - return allAttributes; - } + private static final Gson GSON = new GsonBuilder() + .disableHtmlEscaping() + .setPrettyPrinting() + .create(); + + public static String getGameVersion() { + SharedConstants.tryDetectVersion(); + return SharedConstants.getCurrentVersion().getName(); + } + + public static String getArg(String[] args, String argName, String defaultValue) { + for (int i = 0; i < args.length; i++) { + if (args[i].equals(argName)) { + return args[i + 1]; + } + } + return defaultValue; + } + + public static void main(String[] args) { + final boolean write = true; + + var mcVersion = getGameVersion(); + System.err.println("Initializing Minecraft " + mcVersion + " registries ..."); + Bootstrap.bootStrap(); + System.err.println("Done."); + + // Get --outputDir from args + var outputDir = getArg(args, "--outputDir", "output"); + if (!outputDir.isEmpty() && !outputDir.endsWith("/")) { + outputDir += "/"; + } + + // make the output directory if it doesn't exist + var outputDirPath = Paths.get(outputDir); + try { + Files.createDirectories(outputDirPath); + } catch (IOException e) { + e.printStackTrace(); + System.err.println("Failed to create output directory."); + } + System.err.println("Extraction output directory: " + outputDir); + + var blockShapesJson = doBlockShapeExtraction(); + var blockPropertiesJson = doBlockPropertyExtraction(); + var attributesJson = doAttributeExtraction(); + + if (write) { + // Block shapes + try { + writeJson(outputDirPath.resolve("blockCollisionShapes.json"), blockShapesJson); + System.err.println("Done with block shapes."); + } catch (IOException e) { + e.printStackTrace(); + System.err.println("Failed to write block shapes."); + } + + // Blocks + try { + writeJson(outputDirPath.resolve("blockProperties.json"), blockPropertiesJson); + System.err.println("Done with block shapes."); + } catch (IOException e) { + e.printStackTrace(); + System.err.println("Failed to write block shapes."); + } + + // Attributes + try { + writeJson(outputDirPath.resolve("attributes.json"), attributesJson); + System.err.println("Done with attributes."); + } catch (IOException e) { + e.printStackTrace(); + System.err.println("Failed to write attributes."); + } + } + + System.err.println("Running collision sanity checks ..."); + var failures = runSanityChecks(new BlockCollisionBoxStorage(blockShapesJson)); + System.err.println(failures.size() + " failures."); + } + + public static JsonObject doBlockShapeExtraction() { + System.err.println("Extracting Block shape data ..."); + var blockShapesJson = extractBlockCollisionShapes(); + System.err.println("Extracted data for " + blockShapesJson.getAsJsonObject("blocks").size() + " blocks" + + " and " + blockShapesJson.getAsJsonObject("shapes").size() + " distinct shapes."); + return blockShapesJson; + } + + public static JsonObject doBlockPropertyExtraction() { + System.err.println("Extracting Block data ..."); + var blockPropertiesJson = extractBlockProperties(); + System.err.println("Extracted data for " + blockPropertiesJson.size() + " blocks."); + return blockPropertiesJson; + } + + public static JsonObject doAttributeExtraction() { + System.err.println("Extracting Attribute data ..."); + var attributesJson = extractAttributes(); + System.err.println("Extracted data for " + attributesJson.size() + " attributes."); + return attributesJson; + } + + public static void writeJson(Path path, JsonObject json) throws IOException { + System.err.println("Writing to '" + path + "'..."); + Files.writeString(path, GSON.toJson(json)); + } + + // COLLISIONS + + /** + * output data structure: + *
+     * {
+     *   "shapes": { [shape]: [[x1,y1,z1, x2,y2,z2], ...] },
+     *   "blocks": {
+     *     [block]: shape, // all block states have same shape
+     *     [block]: [ shape, ... ], // at least one state shape different from others; indexed by stateId
+     *     ...
+     *   }
+     * }
+     * 
+ */ + private static JsonObject extractBlockCollisionShapes() { + var allBlocksJson = new JsonObject(); + var shapeIds = new HashMap(); + + for (var block : BuiltInRegistries.BLOCK) { + var states = block.getStateDefinition().getPossibleStates(); + var boxesByState = new int[states.size()]; + + var state0Shape = new Shape(block.defaultBlockState()); + var state0ShapeId = lookupAndPersistShapeId(state0Shape, shapeIds); + boolean allSame = true; + + for (int stateId = 0; stateId < states.size(); stateId++) { + var blockState = states.get(stateId); + + var stateShape = new Shape(blockState); + var stateShapeId = lookupAndPersistShapeId(stateShape, shapeIds); + boxesByState[stateId] = stateShapeId; + + if (allSame && !Objects.equals(state0ShapeId, stateShapeId)) { + allSame = false; + } + } + + var blockId = getBlockIdString(block); + if (allSame) { + allBlocksJson.addProperty(blockId, state0ShapeId); + } else { + var blockJson = new JsonArray(); + for (int shapeId : boxesByState) { + blockJson.add(shapeId); + } + allBlocksJson.add(blockId, blockJson); + + System.err.println(blockId + ": " + boxesByState.length + " states, " + + (boxesByState.length - blockJson.size()) + " empty"); + } + } + + var allShapesJson = new JsonObject(); + shapeIds.entrySet().stream().sorted(Map.Entry.comparingByValue()) + .forEach(entry -> allShapesJson.add(entry.getValue().toString(), entry.getKey().toJson())); + + var rootJson = new JsonObject(); + rootJson.add("blocks", allBlocksJson); + rootJson.add("shapes", allShapesJson); + return rootJson; + } + + private static List runSanityChecks(BlockCollisionBoxStorage storage) { + var failures = new ArrayList(); + for (var block : BuiltInRegistries.BLOCK) { + var blockId = getBlockIdString(block); + var states = block.getStateDefinition().getPossibleStates(); + for (int stateId = 0; stateId < states.size(); stateId++) { + var blockState = states.get(stateId); + + var mcShape = new Shape(blockState); + var storageShape = storage.getBlockShape(blockId, stateId); + + if (!mcShape.equals(storageShape)) { + System.err.println("ERROR: shapes differ: block=" + blockId + " state=" + stateId); + failures.add(blockId + ":" + stateId); + } + } + } + return failures; + } + + private static Integer lookupAndPersistShapeId(Shape shape, HashMap shapeIds) { + return shapeIds.computeIfAbsent(shape, s -> shapeIds.size()); + } + + private static String getBlockIdString(Block block) { + return BuiltInRegistries.BLOCK.getKey(block).getPath(); + } + + // ATTRIBUTES + public static JsonObject extractAttributes() { + var allAttributes = new JsonObject(); + for (var attr : BuiltInRegistries.ATTRIBUTE) { + var attrJson = new JsonObject(); + attrJson.addProperty("default", attr.getDefaultValue()); + if (attr instanceof RangedAttribute rangedAttr) { + attrJson.addProperty("min", rangedAttr.getMinValue()); + attrJson.addProperty("max", rangedAttr.getMaxValue()); + } + + var key = BuiltInRegistries.ATTRIBUTE.getKey(attr); + if (key == null) { + System.err.println("ERROR: attribute has no key: " + attr); + continue; + } + attrJson.addProperty("description", attr.getDescriptionId()); + attrJson.addProperty("id", BuiltInRegistries.ATTRIBUTE.getId(attr)); + allAttributes.add(key.toString(), attrJson); + } + return allAttributes; + } + + @SuppressWarnings("unchecked") + private static Optional getOffsetFunction(BlockState block) { + try { + Field offsetFunctionField = BlockBehaviour.BlockStateBase.class.getDeclaredField("offsetFunction"); + offsetFunctionField.setAccessible(true); + + return (Optional) offsetFunctionField.get(block); + } catch (ReflectiveOperationException e) { + throw new RuntimeException(e); + } + } + + // BLOCKS + private static JsonObject extractBlockProperties() { + var rootJson = new JsonObject(); + + var sawZeroYOffset = false; + var sawNonZeroYOffset = false; + for (var block : BuiltInRegistries.BLOCK) { + var blockData = new JsonObject(); + + var propertyArray = new JsonArray(); + + // Blocks share properties with all states + var defaultState = block.defaultBlockState(); + if (defaultState.hasOffsetFunction()) { + var offsetData = new JsonObject(); + offsetData.addProperty("maxHorizontalOffset", block.getMaxHorizontalOffset()); + offsetData.addProperty("maxVerticalOffset", block.getMaxVerticalOffset()); + + var offsetFunction = getOffsetFunction(defaultState).orElseThrow(); + var vec = offsetFunction.evaluate(Blocks.GRASS.defaultBlockState(), EmptyBlockGetter.INSTANCE, new BlockPos(1, 2, 3)); + + String offsetType; + if (vec.y == 0.0) { + sawZeroYOffset = true; + offsetType = "XZ"; + } else { + sawNonZeroYOffset = true; + offsetType = "XYZ"; + } + + offsetData.addProperty("type", offsetType); + + blockData.add("offsetData", offsetData); + } + + if (defaultState.canBeReplaced()) { + propertyArray.add("replaceable"); + } + + if (defaultState.isAir()) { + propertyArray.add("air"); + } + + if (defaultState.requiresCorrectToolForDrops()) { + propertyArray.add("requiresCorrectToolForDrops"); + } + + if (block instanceof FallingBlock) { + propertyArray.add("fallingBlock"); + } + + blockData.add("properties", propertyArray); + + rootJson.add(getBlockIdString(block), blockData); + } + + // Some validation to make sure we're not missing anything + if (!sawZeroYOffset || !sawNonZeroYOffset) { + throw new IllegalStateException("Didn't see both zero and non-zero Y offsets"); + } + + return rootJson; + } } diff --git a/src/main/java/mcextract/Shape.java b/src/main/java/mcextract/Shape.java index 2ffb777..f761985 100644 --- a/src/main/java/mcextract/Shape.java +++ b/src/main/java/mcextract/Shape.java @@ -1,58 +1,65 @@ package mcextract; import com.google.gson.JsonArray; -import net.minecraft.world.level.block.state.BlockState; import net.minecraft.core.BlockPos; -import net.minecraft.world.phys.AABB; import net.minecraft.world.level.EmptyBlockGetter; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; -import java.util.*; +import java.util.Collection; +import java.util.Collections; +import java.util.Objects; /** - * The shape of a {@link BlockState}, composed of one or more axis-aligned {@link Box}es. + * The shape of a {@link BlockState}, composed of one or more axis-aligned AABBs. */ public class Shape { - public static final Shape EMPTY = new Shape(Collections.emptyList()); - - public final Collection boxes; - - public Shape(Collection boxes) { - this.boxes = boxes; - } - - public Shape(BlockState blockState) { - this(blockState.getCollisionShape(EmptyBlockGetter.INSTANCE, BlockPos.ZERO).toAabbs()); - } - - public JsonArray toJson() { - final JsonArray boxesJson = new JsonArray(); - for (AABB box : boxes) { - boxesJson.add(jsonArrayFromBox(box)); - } - return boxesJson; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Shape shape = (Shape) o; - return Objects.equals(boxes, shape.boxes); - } - - @Override - public int hashCode() { - return Objects.hash(boxes); - } - - public static JsonArray jsonArrayFromBox(AABB box) { + public static final Shape EMPTY = new Shape(Collections.emptyList()); + + public final Collection boxes; + + public Shape(Collection boxes) { + this.boxes = boxes; + } + + public Shape(BlockState blockState) { + var collisionShape = blockState.getCollisionShape(EmptyBlockGetter.INSTANCE, BlockPos.ZERO); + var offset = blockState.getOffset(EmptyBlockGetter.INSTANCE, BlockPos.ZERO); + var reversedOffset = offset.reverse(); + var collisionShapeWithoutOffset = collisionShape.move(reversedOffset.x, reversedOffset.y, reversedOffset.z); + + this.boxes = collisionShapeWithoutOffset.toAabbs(); + } + + public static JsonArray jsonArrayFromBox(AABB box) { final JsonArray boxJson = new JsonArray(); boxJson.add(box.minX); - boxJson.add(box.minY); - boxJson.add(box.minZ); - boxJson.add(box.maxX); - boxJson.add(box.maxY); - boxJson.add(box.maxZ); - return boxJson; - } + boxJson.add(box.minY); + boxJson.add(box.minZ); + boxJson.add(box.maxX); + boxJson.add(box.maxY); + boxJson.add(box.maxZ); + return boxJson; + } + + public JsonArray toJson() { + final JsonArray boxesJson = new JsonArray(); + for (AABB box : boxes) { + boxesJson.add(jsonArrayFromBox(box)); + } + return boxesJson; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Shape shape = (Shape) o; + return Objects.equals(boxes, shape.boxes); + } + + @Override + public int hashCode() { + return Objects.hash(boxes); + } }