Compare commits

..

140 Commits

Author SHA1 Message Date
dfsek 712df89064 convert to new expression switches 2021-05-15 21:24:58 -07:00
dfsek ad41c9bd7d bump language level to Java 14 2021-05-15 20:57:50 -07:00
dfsek 806b9080f0 add Jabel annotation processor 2021-05-15 20:56:14 -07:00
dfsek a05f837ca2 Merge pull request #183 from PolyhedralDev/dev/cleanup/gradleproperties
Update mod description and use Gradle properties so we dont forget some platforms if we change things in the future
2021-05-15 14:20:44 -07:00
dfsek 6fbb5d712e add license, wiki, source and issue URLs to properties 2021-05-14 23:30:36 -07:00
dfsek 2c9d195474 remove unused command from bukkit manifest 2021-05-14 23:09:21 -07:00
dfsek b663d34320 add DESCRIPTION to processResources 2021-05-14 23:09:08 -07:00
dfsek 43095d0df1 add version stuff to plugin/mod manifests 2021-05-14 23:05:22 -07:00
dfsek 47e0dc862c add Terra description and mod ID to gradle.properties 2021-05-14 23:02:14 -07:00
dfsek 460b11b9c8 Merge pull request #182 from PolyhedralDev/dev/forge-mixins
Mixinify Forge implementation and fix several issues on Forge
2021-05-14 22:40:05 -07:00
dfsek d974a72cb9 fix commands on forge 2021-05-14 22:36:55 -07:00
dfsek e86f37fdfb Forge build hacks 2021-05-14 22:30:27 -07:00
dfsek 2ed120dc4c forge cleanup 2021-05-14 19:15:13 -07:00
dfsek 973ae785f4 Forge server fixes 2021-05-14 18:40:03 -07:00
dfsek 4835813e2e fix chunk generator reset on forge 2021-05-14 18:25:28 -07:00
dfsek 632409050b Merge remote-tracking branch 'origin/master' into dev/forge-mixins
# Conflicts:
#	gradle.properties
2021-05-14 17:47:50 -07:00
dfsek 9d991dbb97 Merge pull request #181 from PolyhedralDev/dev/fabric-worldedit
Implement WorldEdit integration for structure exporting on Fabric
2021-05-14 09:38:13 -07:00
dfsek cddf7c20e4 bump version 2021-05-13 22:10:35 -07:00
dfsek 5fd2fc59f4 worldedit integration on Fabric 2021-05-13 21:28:49 -07:00
dfsek 97d7ccacbf add worldedit dependency 2021-05-13 18:15:07 -07:00
dfsek 0ab949174a Update README.md 2021-05-11 16:06:37 -07:00
dfsek 2bfaa95a81 add forge disclaimer to README 2021-05-11 16:03:32 -07:00
dfsek 96de1554f1 disable configureondemand 2021-05-11 15:56:53 -07:00
dfsek f83dcd802c Merge remote-tracking branch 'origin/master' 2021-05-11 09:03:14 -07:00
dfsek 808aa50f5f update config.yml 2021-05-11 09:02:59 -07:00
dfsek e00271e493 Merge pull request #162 from PolyhedralDev/dev/fabric-late-init
initialize later
2021-05-10 23:14:57 -07:00
dfsek 76bf245e16 type check ChunkGenerator in PopulatorFeature 2021-05-10 22:52:34 -07:00
dfsek 37e441206a fix getHandle overwrite conflicts and annotate getHandle methods as @Intrinsic. 2021-05-10 01:11:22 -07:00
dfsek 5376f7e22e fix server init 2021-05-10 01:03:13 -07:00
dfsek 1186fc6624 bump version 2021-05-05 15:24:55 -07:00
dfsek a1b3680643 initialize later 2021-05-05 15:22:02 -07:00
dfsek 501399919f implement vanilla carver/structure options on Fabric & Forge (we will still yell at you if you use them) 2021-05-04 22:40:37 -07:00
dfsek 725d57d967 rename mixins for mojmap 2021-05-04 22:35:30 -07:00
dfsek a821501392 refactor forge stuff 2021-05-04 22:09:50 -07:00
dfsek d3458148bd default disable forge registry dump 2021-05-04 21:38:44 -07:00
dfsek df4da810ec fix forge mixin issues 2021-05-04 21:37:36 -07:00
dfsek 8f47c84c8e fix forge builds 2021-05-04 21:29:07 -07:00
dfsek f61a544a57 account for null ignored in StructureLocateEvent 2021-05-04 20:32:22 -07:00
dfsek 3217d66c69 forge mixins (probably dont work yet) 2021-05-04 19:22:10 -07:00
dfsek fd48f5f110 Merge pull request #158 from PolyhedralDev/dev/fabric-locate
Override structure location on Fabric
2021-05-04 16:45:25 -07:00
dfsek 77a4c95c4a override structure location on Fabric 2021-05-04 16:44:43 -07:00
dfsek dbc60b1d82 Merge pull request #153 from PolyhedralDev/dev/fabric-mixins
Implement Terra interfaces directly in Minecraft classes using Mixin.
2021-05-04 16:16:31 -07:00
dfsek ed942bb997 update README.md 2021-05-04 16:13:05 -07:00
dfsek 6866084872 SignBlockEntityMixin cleanup 2021-05-04 16:10:37 -07:00
dfsek 4c77419dcd fix sign getText on server 2021-05-04 15:04:53 -07:00
dfsek ecba6e0843 Merge remote-tracking branch 'origin/dev/fabric-mixins' into dev/fabric-mixins 2021-05-04 09:21:21 -07:00
dfsek 86dcb476f1 update README with modern build instructions and Forge download links 2021-05-04 09:21:12 -07:00
dfsek 13e0857882 merge FabricEnumAdapter into FabricAdapter 2021-05-03 22:49:21 -07:00
dfsek bf93a9239c bump version 2021-05-03 22:28:01 -07:00
dfsek 2d18aab709 fix funky yaml formatting 2021-05-03 22:13:42 -07:00
dfsek a1359da374 terrascript trig functions 2021-05-03 22:13:32 -07:00
dfsek f7bda835f9 fix itemmeta application 2021-05-03 20:52:03 -07:00
dfsek 7595896831 fix refmap issues 2021-05-03 20:40:56 -07:00
dfsek 6614d19845 suppress warnings 2021-05-03 20:14:06 -07:00
dfsek 6209b86560 mixin maintenance 2021-05-03 20:12:48 -07:00
dfsek a30859a3d4 dont try to remap Terra interfaces 2021-05-03 20:08:13 -07:00
dfsek ddbb46289b add package-info.java to implementation mixin package. 2021-05-03 20:03:25 -07:00
dfsek 64c35a9609 refactor Fabric project 2021-05-03 20:02:08 -07:00
dfsek f21069ab2e fix cache misses 2021-05-03 19:43:52 -07:00
dfsek 457729b832 replace most access wideners with mixins 2021-05-03 19:33:57 -07:00
dfsek 756f04a0b3 implement LockableContainerBlockEntityMixin 2021-05-03 18:38:40 -07:00
dfsek 5ee32cc3ba add ConfiguredFeatureMixin 2021-05-03 17:35:43 -07:00
dfsek 955558bc21 implement BlockMixin 2021-05-03 11:37:54 -07:00
dfsek c43a872c23 finish blockstate mixins 2021-05-03 11:27:36 -07:00
dfsek de41b92d5d add SignBlockEntityMixin 2021-05-03 10:27:40 -07:00
dfsek 03091230ed refactor mixins 2021-05-03 10:09:21 -07:00
dfsek a8c88915ea override chunkregion hashcode 2021-05-02 23:39:40 -07:00
dfsek 4cd4720101 fix loot NPE 2021-05-02 23:08:54 -07:00
dfsek 3b9280b19c start work on state mixins 2021-05-02 23:00:21 -07:00
dfsek 2d27e07441 implement BiomeMixin 2021-05-02 22:49:57 -07:00
dfsek 20a5762d2e refactor mixins 2021-05-02 22:48:21 -07:00
dfsek 146f71f704 finish World mixins 2021-05-02 22:45:34 -07:00
dfsek 1d4b0bc100 cleanup 2021-05-02 22:26:23 -07:00
dfsek 138ee0a448 refactor fabric handles 2021-05-02 22:22:32 -07:00
dfsek 2c8cae9d45 create ChunkGeneratorMixin 2021-05-02 22:21:50 -07:00
dfsek 061d2b6493 implement EntityTypeMixin 2021-05-02 21:48:06 -07:00
dfsek e71df936ab EnchantmentMixin 2021-05-02 21:35:39 -07:00
dfsek f4253acb78 item mixins 2021-05-02 21:27:25 -07:00
dfsek c12518fa49 delete FabricItem.java 2021-05-02 21:11:09 -07:00
dfsek 4704b2ebf7 implement ItemMixin 2021-05-02 21:10:48 -07:00
dfsek 89fdfdfb34 suppress warnings 2021-05-02 20:42:54 -07:00
dfsek 35d85f2aa3 PlayerEntityMixin and EntityMixin 2021-05-02 20:38:25 -07:00
dfsek c0368f1c6d implement ServerCommandSourceMixin 2021-05-02 20:17:59 -07:00
dfsek abc069046c add ProtoChunkMixin and WorldChunkMixin 2021-05-02 20:13:24 -07:00
dfsek 46d0b08068 implement ChunkRegionMixin 2021-05-02 19:49:59 -07:00
dfsek a7e3a0286e add -forge and -fabric to Modrinth version numbers. 2021-05-02 17:46:55 -07:00
dfsek 6da8924868 Merge pull request #145 from PolyhedralDev/dev/forge
Forge implementation
2021-05-02 17:38:56 -07:00
dfsek d9dd6afe4b Merge pull request #143 from solonovamax/improvement/better-gradle-performance
Improve gradle performance significantly
2021-05-02 17:37:36 -07:00
dfsek dfec26f789 fix forge modrinth task 2021-05-02 17:21:05 -07:00
dfsek d13be5e159 add Forge modrinth publish task 2021-05-02 17:16:03 -07:00
dfsek 51c5f70d64 forge jarfile nightmare "solution" 2021-05-02 17:08:59 -07:00
dfsek 05b1902c06 Merge pull request #151 from DJtheRedstoner/patch-mixin-ap
Fix mixin annotation processor issues
2021-05-02 15:47:32 -07:00
dfsek f4ae2cac68 add MixinGeneratorOptions 2021-05-02 15:46:03 -07:00
dfsek ea3995afce fix refmap name 2021-05-02 15:44:30 -07:00
dfsek c41d60c38f remove manual refmap 2021-05-02 15:43:12 -07:00
DJtheRedstoner 19edcbddd5 Fix mixin annotation processor issues
These issues were caused by CompilationConfig.configureCompilation()
overwriting JavaCompile's options.compilerArgs list which removed any
previously added arguments, including those added by fabric-loom and
mixingradle.
2021-05-02 18:17:18 -04:00
dfsek 4f65555e82 remove mixins until annotation processor gets fixed. 2021-05-02 14:37:34 -07:00
dfsek 9956cab507 dont use vanilla registries 2021-05-01 22:21:27 -07:00
dfsek fddf0c51b7 cleanup PopulationManager 2021-05-01 20:27:59 -07:00
dfsek e2a52afb67 remove methods only used for cursed Bukkit stuff from common World interface. 2021-05-01 19:07:19 -07:00
dfsek c8c3a33912 fix loot table issue 2021-05-01 18:40:31 -07:00
dfsek b178f69e47 Merge remote-tracking branch 'origin/dev/forge' into dev/forge 2021-05-01 18:20:23 -07:00
dfsek 049a56fcb0 Mixin on Forge 2021-05-01 18:20:11 -07:00
solonovamax 2d41dd8f08 Don't use all cores processors for tests
Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>
2021-05-01 16:53:45 -04:00
solonovamax aa9e33af1d Remove old and deprecated compile configuration + some minor refactoring
Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>
2021-05-01 16:53:45 -04:00
dfsek 02870805c7 hoist calculations in chunk generator 2021-04-30 09:35:15 -07:00
dfsek e493825ab7 bump version 2021-04-30 09:25:56 -07:00
dfsek 762b248641 update to latest Tectonic 2021-04-29 23:42:56 -07:00
dfsek f81ccee020 cleanup 2021-04-29 23:31:03 -07:00
dfsek 3561e5f30f commands on Forge 2021-04-29 23:19:49 -07:00
dfsek c67817b9d2 fix structure issues 2021-04-29 22:00:40 -07:00
dfsek 756619edb6 Forge actually loads to worlds now 2021-04-29 21:48:32 -07:00
dfsek ee1c889d54 world screen type 2021-04-29 21:11:26 -07:00
dfsek 9f3dcf07b6 Pack loading on Forge 2021-04-29 20:30:48 -07:00
dfsek 93a2f103f7 add pack.mcmeta 2021-04-29 16:41:14 -07:00
dfsek 3ea12ceeab start implementing terraplugin 2021-04-29 12:30:17 -07:00
dfsek ce8ec51ae4 forge actually loads now 2021-04-29 12:24:29 -07:00
dfsek 54bb4ef109 sort of working Forge project 2021-04-29 01:55:24 -07:00
dfsek 59b655ce5d working forge buildscript 2021-04-29 01:27:28 -07:00
solonovamax 4c1e1bb7d5 Improve gradle performance significantly
Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>
2021-04-28 20:43:53 -04:00
dfsek eee54f507e Merge pull request #138 from PolyhedralDev/dev/profilerimpl
Fancy stack-based profiler
2021-04-26 21:32:42 -07:00
dfsek 6f1b1611ab fix dumb gradle issue 2021-04-26 21:26:44 -07:00
dfsek 205499220d profile more things 2021-04-26 20:59:21 -07:00
dfsek a0c5631eba bump version 2021-04-26 20:46:36 -07:00
dfsek 9323abc788 document Profiler 2021-04-26 19:04:20 -07:00
dfsek 632f898dc8 implement Profiler#reset 2021-04-26 19:01:53 -07:00
dfsek 8737b0d984 resolve merge conflict 2021-04-25 17:12:42 -07:00
dfsek bcb68853d5 @SuppressWarnings go brrr 2021-04-25 17:11:50 -07:00
dfsek 8823d6d65e fix stack size assumption at profiler start 2021-04-25 17:11:50 -07:00
dfsek 5d3a2b6e84 profile more things 2021-04-25 17:11:50 -07:00
dfsek 23fb7753ab fancy unicode symbols B) 2021-04-25 17:11:50 -07:00
dfsek f8e7e343cb fix % parent issue 2021-04-25 17:11:50 -07:00
dfsek e5f4c5dc8d implement terrascript profiling 2021-04-25 17:11:49 -07:00
dfsek 8a10867e5f implement new profiler 2021-04-25 17:11:04 -07:00
dfsek da366a75e8 add autocloseable option 2021-04-25 17:09:08 -07:00
dfsek eb4bf74cc6 implement TerraPlugin#getProfier 2021-04-25 17:09:08 -07:00
dfsek 168c0ced13 improve performance in deep operations 2021-04-25 17:09:07 -07:00
dfsek 5d4bdb431b improve data output 2021-04-25 17:09:07 -07:00
dfsek 40188c671f basic profiler implementation 2021-04-25 17:09:07 -07:00
dfsek f396e0e5eb Merge pull request #133 from PolyhedralDev/ver/5.1.4
Fix minor Fabric issues
2021-04-16 09:01:29 -07:00
245 changed files with 5692 additions and 3290 deletions
+1 -1
View File
@@ -342,6 +342,6 @@ ij_json_wrap_long_lines = false
indent_size = 2
ij_yaml_keep_indents_on_empty_lines = true
ij_yaml_keep_line_breaks = true
ij_yaml_space_before_colon = true
ij_yaml_space_before_colon = false
ij_yaml_spaces_within_braces = true
ij_yaml_spaces_within_brackets = true
+26 -10
View File
@@ -7,24 +7,40 @@ to your specifications, with no knowledge of Java required.
* Paper+ servers (Paper, Tuinity, Purpur, etc): [SpigotMC](https://www.spigotmc.org/resources/85151/)
* Fabric: [Modrinth](https://modrinth.com/mod/terra) / [CurseForge](https://www.curseforge.com/minecraft/mc-mods/terra-world-generator)
* Forge **(ALPHA - NOT PRODUCTION-READY)**: [Modrinth](https://modrinth.com/mod/terra) / [CurseForge](https://www.curseforge.com/minecraft/mc-mods/terra-world-generator)
## Building and running Terra
## Building and Running Terra
To build, simply run `./gradlew build` (`gradlew.bat build` on Windows). This will produce a jar in `build/libs`
called `Terra-[CURRENT VERSION].jar`. You can put this right into your plugins dir, along with the correct Gaea version.
To build, simply run `./gradlew build` (`gradlew.bat build` on Windows). This will build all platforms, and
produce JARs in `platforms/<platform>/build/libs`
If you would like to test it with a default server config, just run `./gradlew setupServer` or
`./gradlew.bat setupServer` to set up the server, then `./gradlew testWithPaper` or `gradlew.bat testWithPaper` to run the server. If you
want a clean installation of the server, re-run the `setupServer` task. This will download a default server config
from [here](https://github.com/PolyhedralDev/WorldGenTestServer)
and install the server in the `target/server` directory, along with all the needed plugins.
### Production JARs:
* Bukkit: `Terra-<version>-shaded.jar`
* Fabric: `Terra-<version>-shaded-mapped.jar`
* Forge: `Terra-<version>-shaded.jar`
**Note: You will need to adjust the `NAME` variable `bukkit.yml` of the test server if you are not using the default Terra config.**
### Building a Specific Platform
To build a specific platform, run `gradlew :platforms:<platform>:build`.
JARs are produced in `platforms/<platform>/build/libs`.
### Running Minecraft in the IDE
To run Minecraft with Terra in the IDE (for testing) use the following tasks:
* Bukkit
* `installPaper` - Install a [Paper](https://github.com/PaperMC/Paper) test server. (Only needs to be run once).
* `installPurpur` - Install a [Purpur](https://github.com/pl3xgaming/Purpur) test server. (Only needs to be run once).
* `runPaper` - Run the Paper test server with Terra (`installPaper` must have been run previously).
* `runPurpur` - Run the Purpur test server with Terra (`installPurpur` must have been run previously).
* Fabric
* `runClient` - Run a Minecraft Fabric client with Terra installed.
* `runServer` - Run a Minecraft Fabric server with Terra installed.
* Forge
* `runClient` - Run a Minecraft Forge client with Terra installed.
* `runServer` - Run a Minecraft Forge server with Terra installed.
## Contributing
Contributions are welcome! If you want to see a feature in Terra, please, open an issue, or implement it yourself and
submit a PR!
Join the discord [here](https://discord.gg/PXUEbbF) if you would like to talk more about the project!
## Beta
Terra is still in beta! While it is stable, it is not feature-complete. There is a lot to be added!
Terra is still in beta! While it is stable, it is not feature-complete. There is a lot to be added!
+18 -1
View File
@@ -1,10 +1,27 @@
import com.dfsek.terra.getGitHash
val versionObj = Version("5", "1", "3", true)
val versionObj = Version("5", "3", "2", true)
allprojects {
version = versionObj
group = "com.dfsek.terra"
tasks.withType<JavaCompile>().configureEach {
options.isFork = true
options.isIncremental = true
}
tasks.withType<Test>().configureEach {
useJUnitPlatform()
maxHeapSize = "2G"
ignoreFailures = false
failFast = true
maxParallelForks = (Runtime.getRuntime().availableProcessors() - 1).takeIf { it > 0 } ?: 1
reports.html.isEnabled = false
reports.junitXml.isEnabled = false
}
}
/**
* Version class that does version stuff.
@@ -7,26 +7,11 @@ import org.gradle.kotlin.dsl.withType
import java.io.ByteArrayOutputStream
fun Project.configureCommon() {
apply(plugin = "java-library")
apply(plugin = "maven-publish")
apply(plugin = "idea")
configureDependencies()
configureCompilation()
configureDistribution()
version = rootProject.version
tasks.withType<Test>().configureEach {
useJUnitPlatform()
maxHeapSize = "2G"
ignoreFailures = false
failFast = true
maxParallelForks = 12
}
}
fun Project.getGitHash(): String {
@@ -3,23 +3,25 @@ package com.dfsek.terra
import org.gradle.api.JavaVersion
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.bundling.Jar
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.api.tasks.javadoc.Javadoc
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.filter
import org.gradle.kotlin.dsl.withType
import org.gradle.kotlin.dsl.*
import org.gradle.language.jvm.tasks.ProcessResources
fun Project.configureCompilation() {
apply(plugin = "maven-publish")
apply(plugin = "idea")
configure<JavaPluginConvention> {
sourceCompatibility = JavaVersion.VERSION_1_8
sourceCompatibility = JavaVersion.VERSION_14
targetCompatibility = JavaVersion.VERSION_1_8
}
tasks.withType<JavaCompile> {
options.encoding = "UTF-8"
doFirst {
options.compilerArgs = mutableListOf("-Xlint:all")
options.compilerArgs.addAll(arrayOf("-Xlint:all", "--release", "8", "-Xplugin:jabel"))
}
}
@@ -27,7 +29,12 @@ fun Project.configureCompilation() {
include("**/*.*")
filter<org.apache.tools.ant.filters.ReplaceTokens>(
"tokens" to mapOf(
"VERSION" to project.version.toString()
"VERSION" to project.version.toString(),
"DESCRIPTION" to project.properties["terra.description"],
"WIKI" to project.properties["terra.wiki"],
"SOURCE" to project.properties["terra.source"],
"ISSUES" to project.properties["terra.issues"],
"LICENSE" to project.properties["terra.license"]
)
)
}
@@ -35,4 +42,19 @@ fun Project.configureCompilation() {
tasks.withType<Javadoc> {
options.encoding = "UTF-8"
}
tasks.withType<Jar> {
archiveBaseName.set("Terra-${archiveBaseName.get()}")
from("../LICENSE", "../../LICENSE")
}
tasks.register<Jar>("sourcesJar") {
archiveClassifier.set("sources")
}
tasks.register<Jar>("javadocJar") {
dependsOn("javadoc")
archiveClassifier.set("javadoc")
from(tasks.getByName<Javadoc>("javadoc").destinationDir)
}
}
@@ -1,13 +1,27 @@
package com.dfsek.terra
import org.gradle.api.Project
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.invoke
import org.gradle.kotlin.dsl.repositories
fun Project.configureDependencies() {
apply(plugin = "java")
apply(plugin = "java-library")
configurations {
val shaded = create("shaded")
val shadedApi = create("shadedApi")
shaded.extendsFrom(shadedApi)
getByName("api").extendsFrom(shadedApi)
val shadedImplementation = create("shadedImplementation")
shaded.extendsFrom(shadedImplementation)
getByName("implementation").extendsFrom(shadedImplementation)
}
repositories {
maven { url = uri("http://maven.enginehub.org/repo/") }
maven { url = uri("https://maven.enginehub.org/repo/") }
maven { url = uri("https://repo.codemc.org/repository/maven-public") }
maven { url = uri("https://papermc.io/repo/repository/maven-public/") }
maven { url = uri("https://maven.fabricmc.net/") }
@@ -19,6 +33,7 @@ fun Project.configureDependencies() {
dependencies {
"testImplementation"("org.junit.jupiter:junit-jupiter-api:5.7.0")
"testImplementation"("org.junit.jupiter:junit-jupiter-engine:5.7.0")
"compileOnly"("org.jetbrains:annotations:20.1.0")
"annotationProcessor"("com.github.bsideup.jabel:jabel-javac-plugin:0.3.0")
"api"("org.jetbrains:annotations:20.1.0")
}
}
@@ -14,17 +14,6 @@ fun Project.configureDistribution() {
apply(plugin = "java-library")
apply(plugin = "com.github.johnrengelman.shadow")
configurations {
val shaded = create("shaded")
getByName("compile").extendsFrom(shaded)
val shadedApi = create("shadedApi")
shaded.extendsFrom(shadedApi)
getByName("api").extendsFrom(shadedApi)
val shadedImplementation = create("shadedImplementation")
shaded.extendsFrom(shadedImplementation)
getByName("implementation").extendsFrom(shadedImplementation)
}
val downloadDefaultPacks = tasks.create("downloadDefaultPacks") {
group = "terra"
doFirst {
@@ -38,21 +27,6 @@ fun Project.configureDistribution() {
}
tasks["processResources"].dependsOn(downloadDefaultPacks)
tasks.withType<Jar> {
archiveBaseName.set("Terra-${archiveBaseName.get()}")
from("../LICENSE", "../../LICENSE")
}
tasks.register<Jar>("sourcesJar") {
archiveClassifier.set("sources")
}
tasks.register<Jar>("javadocJar") {
dependsOn("javadoc")
archiveClassifier.set("javadoc")
from(tasks.getByName<Javadoc>("javadoc").destinationDir)
}
tasks.named<ShadowJar>("shadowJar") {
// Tell shadow to download the packs
dependsOn(downloadDefaultPacks)
+6 -3
View File
@@ -1,11 +1,14 @@
import com.dfsek.terra.configureCommon
import com.dfsek.terra.configureCompilation
import com.dfsek.terra.configureDependencies
plugins {
`java-library`
`maven-publish`
idea
}
configureCommon()
configureCompilation()
configureDependencies()
group = "com.dfsek.terra.common"
@@ -14,7 +17,7 @@ dependencies {
"shadedApi"("commons-io:commons-io:2.4")
"shadedApi"("com.dfsek:Paralithic:0.3.2")
"shadedApi"("com.dfsek:Tectonic:1.2.3")
"shadedApi"("com.dfsek:Tectonic:1.3.1")
"shadedApi"("net.jafama:jafama:2.3.2")
"shadedApi"("org.yaml:snakeyaml:1.27")
"shadedApi"("org.ow2.asm:asm:9.0")
@@ -7,14 +7,19 @@ import com.dfsek.terra.api.platform.handle.WorldHandle;
import com.dfsek.terra.api.platform.world.World;
import com.dfsek.terra.api.registry.CheckedRegistry;
import com.dfsek.terra.api.registry.LockedRegistry;
import com.dfsek.terra.api.util.JarUtil;
import com.dfsek.terra.api.util.logging.DebugLogger;
import com.dfsek.terra.api.util.logging.Logger;
import com.dfsek.terra.config.PluginConfig;
import com.dfsek.terra.config.lang.Language;
import com.dfsek.terra.config.pack.ConfigPack;
import com.dfsek.terra.profiler.Profiler;
import com.dfsek.terra.world.TerraWorld;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.jar.JarFile;
/**
* Represents a Terra mod/plugin instance.
@@ -64,4 +69,10 @@ public interface TerraPlugin extends LoaderRegistrar {
default void runPossiblyUnsafeTask(Runnable task) {
task.run();
}
Profiler getProfiler();
default JarFile getModJar() throws URISyntaxException, IOException {
return JarUtil.getJarFile();
}
}
@@ -65,7 +65,7 @@ public class TerraCommandManager implements CommandManager {
return;
}
if(commandClass.isAnnotationPresent(WorldCommand.class) && (!(sender instanceof Player) || !TerraWorld.isTerraWorld(((Player) sender).getWorld()))) {
if(commandClass.isAnnotationPresent(WorldCommand.class) && (!(sender instanceof Player) || !(((Player) sender).getWorld()).isTerraWorld())) {
sender.sendMessage("Command must be executed in a Terra world.");
return;
}
@@ -29,12 +29,8 @@ public class ExpressionSampler implements NoiseSampler {
functions.forEach((id, noise) -> {
switch(noise.getDimensions()) {
case 2:
parser.registerFunction(id, new NoiseFunction2(noise.apply(seed)));
break;
case 3:
parser.registerFunction(id, new NoiseFunction3(noise.apply(seed)));
break;
case 2 -> parser.registerFunction(id, new NoiseFunction2(noise.apply(seed)));
case 3 -> parser.registerFunction(id, new NoiseFunction3(noise.apply(seed)));
}
});
@@ -333,36 +333,21 @@ public class CellularSampler extends NoiseFunction {
}
}
switch(returnType) {
case CellValue:
return closestHash * (1 / 2147483648.0);
case Distance:
return distance0 - 1;
case Distance2:
return distance1 - 1;
case Distance2Add:
return (distance1 + distance0) * 0.5 - 1;
case Distance2Sub:
return distance1 - distance0 - 1;
case Distance2Mul:
return distance1 * distance0 * 0.5 - 1;
case Distance2Div:
return distance0 / distance1 - 1;
case NoiseLookup:
return noiseLookup.getNoise(center.getX(), center.getZ());
case Distance3:
return distance2 - 1;
case Distance3Add:
return (distance2 + distance0) * 0.5 - 1;
case Distance3Sub:
return distance2 - distance0 - 1;
case Distance3Mul:
return distance2 * distance0 - 1;
case Distance3Div:
return distance0 / distance2 - 1;
default:
return 0;
}
return switch(returnType) {
case CellValue -> closestHash * (1 / 2147483648.0);
case Distance -> distance0 - 1;
case Distance2 -> distance1 - 1;
case Distance2Add -> (distance1 + distance0) * 0.5 - 1;
case Distance2Sub -> distance1 - distance0 - 1;
case Distance2Mul -> distance1 * distance0 * 0.5 - 1;
case Distance2Div -> distance0 / distance1 - 1;
case NoiseLookup -> noiseLookup.getNoise(center.getX(), center.getZ());
case Distance3 -> distance2 - 1;
case Distance3Add -> (distance2 + distance0) * 0.5 - 1;
case Distance3Sub -> distance2 - distance0 - 1;
case Distance3Mul -> distance2 * distance0 - 1;
case Distance3Div -> distance0 / distance2 - 1;
};
}
@Override
@@ -507,36 +492,21 @@ public class CellularSampler extends NoiseFunction {
}
}
switch(returnType) {
case CellValue:
return closestHash * (1 / 2147483648.0);
case Distance:
return distance0 - 1;
case Distance2:
return distance1 - 1;
case Distance2Add:
return (distance1 + distance0) * 0.5 - 1;
case Distance2Sub:
return distance1 - distance0 - 1;
case Distance2Mul:
return distance1 * distance0 * 0.5 - 1;
case Distance2Div:
return distance0 / distance1 - 1;
case NoiseLookup:
return noiseLookup.getNoise(center.getX(), center.getY(), center.getZ());
case Distance3:
return distance2 - 1;
case Distance3Add:
return (distance2 + distance0) * 0.5 - 1;
case Distance3Sub:
return distance2 - distance0 - 1;
case Distance3Mul:
return distance2 * distance0 - 1;
case Distance3Div:
return distance0 / distance2 - 1;
default:
return 0;
}
return switch(returnType) {
case CellValue -> closestHash * (1 / 2147483648.0);
case Distance -> distance0 - 1;
case Distance2 -> distance1 - 1;
case Distance2Add -> (distance1 + distance0) * 0.5 - 1;
case Distance2Sub -> distance1 - distance0 - 1;
case Distance2Mul -> distance1 * distance0 * 0.5 - 1;
case Distance2Div -> distance0 / distance1 - 1;
case NoiseLookup -> noiseLookup.getNoise(center.getX(), center.getY(), center.getZ());
case Distance3 -> distance2 - 1;
case Distance3Add -> (distance2 + distance0) * 0.5 - 1;
case Distance3Sub -> distance2 - distance0 - 1;
case Distance3Mul -> distance2 * distance0 - 1;
case Distance3Div -> distance0 / distance2 - 1;
};
}
public enum DistanceFunction {
@@ -83,66 +83,28 @@ public enum BlockFace {
@NotNull
public BlockFace getOppositeFace() {
switch(this) {
case NORTH:
return BlockFace.SOUTH;
return switch(this) {
case NORTH -> BlockFace.SOUTH;
case SOUTH -> BlockFace.NORTH;
case EAST -> BlockFace.WEST;
case WEST -> BlockFace.EAST;
case UP -> BlockFace.DOWN;
case DOWN -> BlockFace.UP;
case NORTH_EAST -> BlockFace.SOUTH_WEST;
case NORTH_WEST -> BlockFace.SOUTH_EAST;
case SOUTH_EAST -> BlockFace.NORTH_WEST;
case SOUTH_WEST -> BlockFace.NORTH_EAST;
case WEST_NORTH_WEST -> BlockFace.EAST_SOUTH_EAST;
case NORTH_NORTH_WEST -> BlockFace.SOUTH_SOUTH_EAST;
case NORTH_NORTH_EAST -> BlockFace.SOUTH_SOUTH_WEST;
case EAST_NORTH_EAST -> BlockFace.WEST_SOUTH_WEST;
case EAST_SOUTH_EAST -> BlockFace.WEST_NORTH_WEST;
case SOUTH_SOUTH_EAST -> BlockFace.NORTH_NORTH_WEST;
case SOUTH_SOUTH_WEST -> BlockFace.NORTH_NORTH_EAST;
case WEST_SOUTH_WEST -> BlockFace.EAST_NORTH_EAST;
case SELF -> BlockFace.SELF;
};
case SOUTH:
return BlockFace.NORTH;
case EAST:
return BlockFace.WEST;
case WEST:
return BlockFace.EAST;
case UP:
return BlockFace.DOWN;
case DOWN:
return BlockFace.UP;
case NORTH_EAST:
return BlockFace.SOUTH_WEST;
case NORTH_WEST:
return BlockFace.SOUTH_EAST;
case SOUTH_EAST:
return BlockFace.NORTH_WEST;
case SOUTH_WEST:
return BlockFace.NORTH_EAST;
case WEST_NORTH_WEST:
return BlockFace.EAST_SOUTH_EAST;
case NORTH_NORTH_WEST:
return BlockFace.SOUTH_SOUTH_EAST;
case NORTH_NORTH_EAST:
return BlockFace.SOUTH_SOUTH_WEST;
case EAST_NORTH_EAST:
return BlockFace.WEST_SOUTH_WEST;
case EAST_SOUTH_EAST:
return BlockFace.WEST_NORTH_WEST;
case SOUTH_SOUTH_EAST:
return BlockFace.NORTH_NORTH_WEST;
case SOUTH_SOUTH_WEST:
return BlockFace.NORTH_NORTH_EAST;
case WEST_SOUTH_WEST:
return BlockFace.EAST_NORTH_EAST;
case SELF:
return BlockFace.SELF;
}
return BlockFace.SELF;
}
}
@@ -1,6 +1,7 @@
package com.dfsek.terra.api.platform.inventory;
import com.dfsek.terra.api.platform.Handle;
import com.dfsek.terra.api.platform.inventory.item.Damageable;
import com.dfsek.terra.api.platform.inventory.item.ItemMeta;
public interface ItemStack extends Handle {
@@ -13,4 +14,8 @@ public interface ItemStack extends Handle {
ItemMeta getItemMeta();
void setItemMeta(ItemMeta meta);
default boolean isDamageable() {
return getItemMeta() instanceof Damageable;
}
}
@@ -6,6 +6,8 @@ import com.dfsek.terra.api.platform.block.Block;
import com.dfsek.terra.api.platform.entity.Entity;
import com.dfsek.terra.api.platform.entity.EntityType;
import com.dfsek.terra.api.platform.world.generator.ChunkGenerator;
import com.dfsek.terra.api.platform.world.generator.GeneratorWrapper;
import com.dfsek.terra.api.world.generation.TerraChunkGenerator;
import java.io.File;
import java.util.UUID;
@@ -17,20 +19,12 @@ public interface World extends Handle {
ChunkGenerator getGenerator();
String getName();
UUID getUID();
boolean isChunkGenerated(int x, int z);
Chunk getChunkAt(int x, int z);
default Chunk getChunkAt(Location location) {
return getChunkAt(location.getBlockX() >> 4, location.getBlockZ() >> 4);
}
File getWorldFolder();
Block getBlockAt(int x, int y, int z);
default Block getBlockAt(Location l) {
@@ -40,4 +34,12 @@ public interface World extends Handle {
Entity spawnEntity(Location location, EntityType entityType);
int getMinHeight();
default boolean isTerraWorld() {
return getGenerator().getHandle() instanceof GeneratorWrapper;
}
default TerraChunkGenerator getTerraGenerator() {
return ((GeneratorWrapper) getGenerator().getHandle()).getHandle();
}
}
@@ -43,8 +43,7 @@ public class Entry {
if(entry.containsKey("functions")) {
for(Object function : (JSONArray) entry.get("functions")) {
switch(((String) ((JSONObject) function).get("function"))) {
case "minecraft:set_count":
case "set_count":
case "minecraft:set_count", "set_count" -> {
Object loot = ((JSONObject) function).get("count");
long max, min;
if(loot instanceof Long) {
@@ -55,22 +54,20 @@ public class Entry {
min = (long) ((JSONObject) loot).get("min");
}
functions.add(new AmountFunction(FastMath.toIntExact(min), FastMath.toIntExact(max)));
break;
case "minecraft:set_damage":
case "set_damage":
}
case "minecraft:set_damage", "set_damage" -> {
long maxDamage = (long) ((JSONObject) ((JSONObject) function).get("damage")).get("max");
long minDamage = (long) ((JSONObject) ((JSONObject) function).get("damage")).get("min");
functions.add(new DamageFunction(FastMath.toIntExact(minDamage), FastMath.toIntExact(maxDamage)));
break;
case "minecraft:enchant_with_levels":
case "enchant_with_levels":
}
case "minecraft:enchant_with_levels", "enchant_with_levels" -> {
long maxEnchant = (long) ((JSONObject) ((JSONObject) function).get("levels")).get("max");
long minEnchant = (long) ((JSONObject) ((JSONObject) function).get("levels")).get("min");
JSONArray disabled = null;
if(((JSONObject) function).containsKey("disabled_enchants"))
disabled = (JSONArray) ((JSONObject) function).get("disabled_enchants");
functions.add(new EnchantFunction(FastMath.toIntExact(minEnchant), FastMath.toIntExact(maxEnchant), disabled, main));
break;
}
}
}
}
@@ -34,8 +34,8 @@ public class DamageFunction implements LootFunction {
@Override
public ItemStack apply(ItemStack original, Random r) {
if(original == null) return null;
if(!original.isDamageable()) return original;
ItemMeta meta = original.getItemMeta();
if(!(meta instanceof Damageable)) return original;
double itemDurability = (r.nextDouble() * (max - min)) + min;
Damageable damage = (Damageable) meta;
damage.setDamage((int) (original.getType().getMaxDurability() - (itemDurability / 100) * original.getType().getMaxDurability()));
@@ -96,16 +96,12 @@ public class Parser {
ParserUtil.checkType(tokens.consume(), Token.Type.GROUP_BEGIN);
switch(identifier.getType()) {
case FOR_LOOP:
return parseForLoop(tokens, variableMap, identifier.getPosition());
case IF_STATEMENT:
return parseIfStatement(tokens, variableMap, identifier.getPosition(), loop);
case WHILE_LOOP:
return parseWhileLoop(tokens, variableMap, identifier.getPosition());
default:
throw new UnsupportedOperationException("Unknown keyword " + identifier.getContent() + ": " + identifier.getPosition());
}
return switch(identifier.getType()) {
case FOR_LOOP -> parseForLoop(tokens, variableMap, identifier.getPosition());
case IF_STATEMENT -> parseIfStatement(tokens, variableMap, identifier.getPosition(), loop);
case WHILE_LOOP -> parseWhileLoop(tokens, variableMap, identifier.getPosition());
default -> throw new UnsupportedOperationException("Unknown keyword " + identifier.getContent() + ": " + identifier.getPosition());
};
}
private WhileKeyword parseWhileLoop(Tokenizer tokens, Map<String, Returnable.ReturnType> variableMap, Position start) throws ParseException {
@@ -233,17 +229,13 @@ public class Parser {
private ConstantExpression<?> parseConstantExpression(Tokenizer tokens) throws ParseException {
Token constantToken = tokens.consume();
Position position = constantToken.getPosition();
switch(constantToken.getType()) {
case NUMBER:
String content = constantToken.getContent();
return new NumericConstant(content.contains(".") ? Double.parseDouble(content) : Integer.parseInt(content), position);
case STRING:
return new StringConstant(constantToken.getContent(), position);
case BOOLEAN:
return new BooleanConstant(Boolean.parseBoolean(constantToken.getContent()), position);
default:
throw new UnsupportedOperationException("Unsupported constant token: " + constantToken.getType() + " at position: " + position);
}
String content = constantToken.getContent();
return switch(constantToken.getType()) {
case NUMBER -> new NumericConstant(content.contains(".") ? Double.parseDouble(content) : Integer.parseInt(content), position);
case STRING -> new StringConstant(content, position);
case BOOLEAN -> new BooleanConstant(Boolean.parseBoolean(content), position);
default -> throw new UnsupportedOperationException("Unsupported constant token: " + constantToken.getType() + " at position: " + position);
};
}
private Returnable<?> parseGroup(Tokenizer tokens, Map<String, Returnable.ReturnType> variableMap) throws ParseException {
@@ -79,16 +79,12 @@ public class ParserUtil {
}
public static Returnable.ReturnType getVariableReturnType(Token varToken) throws ParseException {
switch(varToken.getType()) {
case NUMBER_VARIABLE:
return Returnable.ReturnType.NUMBER;
case STRING_VARIABLE:
return Returnable.ReturnType.STRING;
case BOOLEAN_VARIABLE:
return Returnable.ReturnType.BOOLEAN;
default:
throw new ParseException("Unexpected token " + varToken.getType() + "; expected variable declaration", varToken.getPosition());
}
return switch(varToken.getType()) {
case NUMBER_VARIABLE -> Returnable.ReturnType.NUMBER;
case STRING_VARIABLE -> Returnable.ReturnType.STRING;
case BOOLEAN_VARIABLE -> Returnable.ReturnType.BOOLEAN;
default -> throw new ParseException("Unexpected token " + varToken.getType() + "; expected variable declaration", varToken.getPosition());
};
}
public static boolean hasPrecedence(Token.Type first, Token.Type second) {
@@ -32,15 +32,9 @@ public class Declaration<T> implements Item<T> {
public T apply(ImplementationArguments implementationArguments, Map<String, Variable<?>> variableMap) {
T result = value.apply(implementationArguments, variableMap);
switch(type) {
case NUMBER:
variableMap.put(identifier, new NumberVariable((Number) result, position));
break;
case BOOLEAN:
variableMap.put(identifier, new BooleanVariable((Boolean) result, position));
break;
case STRING:
variableMap.put(identifier, new StringVariable((String) result, position));
break;
case NUMBER -> variableMap.put(identifier, new NumberVariable((Number) result, position));
case BOOLEAN -> variableMap.put(identifier, new BooleanVariable((Boolean) result, position));
case STRING -> variableMap.put(identifier, new StringVariable((String) result, position));
}
return result;
}
@@ -29,6 +29,7 @@ import com.dfsek.terra.api.structures.structure.Rotation;
import com.dfsek.terra.api.structures.structure.buffer.Buffer;
import com.dfsek.terra.api.structures.structure.buffer.DirectBuffer;
import com.dfsek.terra.api.structures.structure.buffer.StructureBuffer;
import com.dfsek.terra.profiler.ProfileFrame;
import com.dfsek.terra.registry.config.FunctionRegistry;
import com.dfsek.terra.registry.config.LootRegistry;
import com.dfsek.terra.registry.config.ScriptRegistry;
@@ -39,6 +40,7 @@ import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Random;
import java.util.concurrent.ExecutionException;
@@ -52,7 +54,7 @@ public class StructureScript {
public StructureScript(InputStream inputStream, TerraPlugin main, ScriptRegistry registry, LootRegistry lootRegistry, FunctionRegistry functionRegistry) throws ParseException {
Parser parser;
try {
parser = new Parser(IOUtils.toString(inputStream));
parser = new Parser(IOUtils.toString(inputStream, Charset.defaultCharset()));
} catch(IOException e) {
throw new RuntimeException(e);
}
@@ -87,6 +89,12 @@ public class StructureScript {
.registerFunction("ceil", new UnaryNumberFunctionBuilder(number -> FastMath.ceil(number.doubleValue())))
.registerFunction("log", new UnaryNumberFunctionBuilder(number -> FastMath.log(number.doubleValue())))
.registerFunction("round", new UnaryNumberFunctionBuilder(number -> FastMath.round(number.doubleValue())))
.registerFunction("sin", new UnaryNumberFunctionBuilder(number -> FastMath.sin(number.doubleValue())))
.registerFunction("cos", new UnaryNumberFunctionBuilder(number -> FastMath.cos(number.doubleValue())))
.registerFunction("tan", new UnaryNumberFunctionBuilder(number -> FastMath.tan(number.doubleValue())))
.registerFunction("asin", new UnaryNumberFunctionBuilder(number -> FastMath.asin(number.doubleValue())))
.registerFunction("acos", new UnaryNumberFunctionBuilder(number -> FastMath.acos(number.doubleValue())))
.registerFunction("atan", new UnaryNumberFunctionBuilder(number -> FastMath.atan(number.doubleValue())))
.registerFunction("max", new BinaryNumberFunctionBuilder((number, number2) -> FastMath.max(number.doubleValue(), number2.doubleValue())))
.registerFunction("min", new BinaryNumberFunctionBuilder((number, number2) -> FastMath.min(number.doubleValue(), number2.doubleValue())));
@@ -104,22 +112,31 @@ public class StructureScript {
* @param rotation Rotation of structure
* @return Whether generation was successful
*/
@SuppressWarnings("try")
public boolean execute(Location location, Random random, Rotation rotation) {
StructureBuffer buffer = new StructureBuffer(location);
boolean level = applyBlock(new TerraImplementationArguments(buffer, rotation, random, 0));
buffer.paste();
return level;
try(ProfileFrame ignore = main.getProfiler().profile("terrascript:" + id)) {
StructureBuffer buffer = new StructureBuffer(location);
boolean level = applyBlock(new TerraImplementationArguments(buffer, rotation, random, 0));
buffer.paste();
return level;
}
}
@SuppressWarnings("try")
public boolean execute(Location location, Chunk chunk, Random random, Rotation rotation) {
StructureBuffer buffer = computeBuffer(location, random, rotation);
buffer.paste(chunk);
return buffer.succeeded();
try(ProfileFrame ignore = main.getProfiler().profile("terrascript_chunk:" + id)) {
StructureBuffer buffer = computeBuffer(location, random, rotation);
buffer.paste(chunk);
return buffer.succeeded();
}
}
@SuppressWarnings("try")
public boolean test(Location location, Random random, Rotation rotation) {
StructureBuffer buffer = computeBuffer(location, random, rotation);
return buffer.succeeded();
try(ProfileFrame ignore = main.getProfiler().profile("terrascript_test:" + id)) {
StructureBuffer buffer = computeBuffer(location, random, rotation);
return buffer.succeeded();
}
}
private StructureBuffer computeBuffer(Location location, Random random, Rotation rotation) {
@@ -134,13 +151,19 @@ public class StructureScript {
}
}
@SuppressWarnings("try")
public boolean executeInBuffer(Buffer buffer, Random random, Rotation rotation, int recursions) {
return applyBlock(new TerraImplementationArguments(buffer, rotation, random, recursions));
try(ProfileFrame ignore = main.getProfiler().profile("terrascript_recursive:" + id)) {
return applyBlock(new TerraImplementationArguments(buffer, rotation, random, recursions));
}
}
@SuppressWarnings("try")
public boolean executeDirect(Location location, Random random, Rotation rotation) {
DirectBuffer buffer = new DirectBuffer(location);
return applyBlock(new TerraImplementationArguments(buffer, rotation, random, 0));
try(ProfileFrame ignore = main.getProfiler().profile("terrascript_direct:" + id)) {
DirectBuffer buffer = new DirectBuffer(location);
return applyBlock(new TerraImplementationArguments(buffer, rotation, random, 0));
}
}
public String getId() {
@@ -28,13 +28,9 @@ public class BiomeFunctionBuilder implements FunctionBuilder<BiomeFunction> {
@Override
public Returnable.ReturnType getArgument(int position) {
switch(position) {
case 0:
case 1:
case 2:
return Returnable.ReturnType.NUMBER;
default:
return null;
}
return switch(position) {
case 0, 1, 2 -> Returnable.ReturnType.NUMBER;
default -> null;
};
}
}
@@ -39,17 +39,11 @@ public class BlockFunctionBuilder implements FunctionBuilder<AbstractBlockFuncti
@Override
public Returnable.ReturnType getArgument(int position) {
switch(position) {
case 0:
case 1:
case 2:
return Returnable.ReturnType.NUMBER;
case 3:
return Returnable.ReturnType.STRING;
case 4:
return Returnable.ReturnType.BOOLEAN;
default:
return null;
}
return switch(position) {
case 0, 1, 2 -> Returnable.ReturnType.NUMBER;
case 3 -> Returnable.ReturnType.STRING;
case 4 -> Returnable.ReturnType.BOOLEAN;
default -> null;
};
}
}
@@ -21,13 +21,9 @@ public class CheckBlockFunctionBuilder implements FunctionBuilder<CheckBlockFunc
@Override
public Returnable.ReturnType getArgument(int position) {
switch(position) {
case 0:
case 1:
case 2:
return Returnable.ReturnType.NUMBER;
default:
return null;
}
return switch(position) {
case 0, 1, 2 -> Returnable.ReturnType.NUMBER;
default -> null;
};
}
}
@@ -6,7 +6,6 @@ import com.dfsek.terra.api.structures.parser.lang.Returnable;
import com.dfsek.terra.api.structures.parser.lang.functions.FunctionBuilder;
import com.dfsek.terra.api.structures.script.functions.CheckFunction;
import com.dfsek.terra.api.structures.tokenizer.Position;
import com.dfsek.terra.world.generation.math.SamplerCache;
import java.util.List;
@@ -30,13 +29,9 @@ public class CheckFunctionBuilder implements FunctionBuilder<CheckFunction> {
@Override
public Returnable.ReturnType getArgument(int position) {
switch(position) {
case 0:
case 1:
case 2:
return Returnable.ReturnType.NUMBER;
default:
return null;
}
return switch(position) {
case 0, 1, 2 -> Returnable.ReturnType.NUMBER;
default -> null;
};
}
}
@@ -29,15 +29,10 @@ public class EntityFunctionBuilder implements FunctionBuilder<EntityFunction> {
@Override
public Returnable.ReturnType getArgument(int position) {
switch(position) {
case 0:
case 1:
case 2:
return Returnable.ReturnType.NUMBER;
case 3:
return Returnable.ReturnType.STRING;
default:
return null;
}
return switch(position) {
case 0, 1, 2 -> Returnable.ReturnType.NUMBER;
case 3 -> Returnable.ReturnType.STRING;
default -> null;
};
}
}
@@ -25,13 +25,9 @@ public class GetMarkFunctionBuilder implements FunctionBuilder<GetMarkFunction>
@Override
public Returnable.ReturnType getArgument(int position) {
switch(position) {
case 0:
case 1:
case 2:
return Returnable.ReturnType.NUMBER;
default:
return null;
}
return switch(position) {
case 0, 1, 2 -> Returnable.ReturnType.NUMBER;
default -> null;
};
}
}
@@ -34,15 +34,10 @@ public class LootFunctionBuilder implements FunctionBuilder<LootFunction> {
@Override
public Returnable.ReturnType getArgument(int position) {
switch(position) {
case 0:
case 1:
case 2:
return Returnable.ReturnType.NUMBER;
case 3:
return Returnable.ReturnType.STRING;
default:
return null;
}
return switch(position) {
case 0, 1, 2 -> Returnable.ReturnType.NUMBER;
case 3 -> Returnable.ReturnType.STRING;
default -> null;
};
}
}
@@ -29,15 +29,10 @@ public class PullFunctionBuilder implements FunctionBuilder<PullFunction> {
@Override
public Returnable.ReturnType getArgument(int position) {
switch(position) {
case 0:
case 1:
case 2:
return Returnable.ReturnType.NUMBER;
case 3:
return Returnable.ReturnType.STRING;
default:
return null;
}
return switch(position) {
case 0, 1, 2 -> Returnable.ReturnType.NUMBER;
case 3 -> Returnable.ReturnType.STRING;
default -> null;
};
}
}
@@ -26,15 +26,10 @@ public class SetMarkFunctionBuilder implements FunctionBuilder<SetMarkFunction>
@Override
public Returnable.ReturnType getArgument(int position) {
switch(position) {
case 0:
case 1:
case 2:
return Returnable.ReturnType.NUMBER;
case 3:
return Returnable.ReturnType.STRING;
default:
return null;
}
return switch(position) {
case 0, 1, 2 -> Returnable.ReturnType.NUMBER;
case 3 -> Returnable.ReturnType.STRING;
default -> null;
};
}
}
@@ -30,15 +30,10 @@ public class StateFunctionBuilder implements FunctionBuilder<StateFunction> {
@Override
public Returnable.ReturnType getArgument(int position) {
switch(position) {
case 0:
case 1:
case 2:
return Returnable.ReturnType.NUMBER;
case 3:
return Returnable.ReturnType.STRING;
default:
return null;
}
return switch(position) {
case 0, 1, 2 -> Returnable.ReturnType.NUMBER;
case 3 -> Returnable.ReturnType.STRING;
default -> null;
};
}
}
@@ -36,13 +36,9 @@ public class StructureFunctionBuilder implements FunctionBuilder<StructureFuncti
@Override
public Returnable.ReturnType getArgument(int position) {
switch(position) {
case 0:
case 1:
case 2:
return Returnable.ReturnType.NUMBER;
default:
return Returnable.ReturnType.STRING;
}
return switch(position) {
case 0, 1, 2 -> Returnable.ReturnType.NUMBER;
default -> Returnable.ReturnType.STRING;
};
}
}
@@ -12,18 +12,13 @@ public enum Rotation {
}
public static Rotation fromDegrees(int deg) {
switch(FastMath.floorMod(deg, 360)) {
case 0:
return Rotation.NONE;
case 90:
return Rotation.CW_90;
case 180:
return Rotation.CW_180;
case 270:
return Rotation.CCW_90;
default:
throw new IllegalArgumentException();
}
return switch(FastMath.floorMod(deg, 360)) {
case 0 -> Rotation.NONE;
case 90 -> Rotation.CW_90;
case 180 -> Rotation.CW_180;
case 270 -> Rotation.CCW_90;
default -> throw new IllegalArgumentException();
};
}
public int getDegrees() {
@@ -31,18 +26,12 @@ public enum Rotation {
}
public Rotation inverse() {
switch(this) {
case NONE:
return NONE;
case CCW_90:
return CW_90;
case CW_90:
return CCW_90;
case CW_180:
return CW_180;
default:
throw new IllegalArgumentException();
}
return switch(this) {
case NONE -> NONE;
case CCW_90 -> CW_90;
case CW_90 -> CCW_90;
case CW_180 -> CW_180;
};
}
public Rotation rotate(Rotation rotation) {
@@ -30,15 +30,9 @@ public class RotationUtil {
public static void rotateVector(Vector2 orig, Rotation r) {
Vector2 copy = orig.clone();
switch(r) {
case CW_90:
copy.setX(orig.getZ()).setZ(-orig.getX());
break;
case CCW_90:
copy.setX(-orig.getZ()).setZ(orig.getX());
break;
case CW_180:
copy.multiply(-1);
break;
case CW_90 -> copy.setX(orig.getZ()).setZ(-orig.getX());
case CCW_90 -> copy.setX(-orig.getZ()).setZ(orig.getX());
case CW_180 -> copy.multiply(-1);
}
orig.setX(copy.getX());
orig.setZ(copy.getZ());
@@ -68,42 +62,25 @@ public class RotationUtil {
* @return integer representation of BlockFace
*/
public static int faceRotation(BlockFace f) {
switch(f) {
case NORTH:
return 0;
case NORTH_NORTH_EAST:
return 1;
case NORTH_EAST:
return 2;
case EAST_NORTH_EAST:
return 3;
case EAST:
return 4;
case EAST_SOUTH_EAST:
return 5;
case SOUTH_EAST:
return 6;
case SOUTH_SOUTH_EAST:
return 7;
case SOUTH:
return 8;
case SOUTH_SOUTH_WEST:
return 9;
case SOUTH_WEST:
return 10;
case WEST_SOUTH_WEST:
return 11;
case WEST:
return 12;
case WEST_NORTH_WEST:
return 13;
case NORTH_WEST:
return 14;
case NORTH_NORTH_WEST:
return 15;
default:
return -1;
}
return switch(f) {
case NORTH -> 0;
case NORTH_NORTH_EAST -> 1;
case NORTH_EAST -> 2;
case EAST_NORTH_EAST -> 3;
case EAST -> 4;
case EAST_SOUTH_EAST -> 5;
case SOUTH_EAST -> 6;
case SOUTH_SOUTH_EAST -> 7;
case SOUTH -> 8;
case SOUTH_SOUTH_WEST -> 9;
case SOUTH_WEST -> 10;
case WEST_SOUTH_WEST -> 11;
case WEST -> 12;
case WEST_NORTH_WEST -> 13;
case NORTH_WEST -> 14;
case NORTH_NORTH_WEST -> 15;
default -> -1;
};
}
/**
@@ -113,42 +90,25 @@ public class RotationUtil {
* @return BlockFace represented by integer.
*/
public static BlockFace fromRotation(int r) {
switch(FastMath.floorMod(r, 16)) {
case 0:
return BlockFace.NORTH;
case 1:
return BlockFace.NORTH_NORTH_EAST;
case 2:
return BlockFace.NORTH_EAST;
case 3:
return BlockFace.EAST_NORTH_EAST;
case 4:
return BlockFace.EAST;
case 5:
return BlockFace.EAST_SOUTH_EAST;
case 6:
return BlockFace.SOUTH_EAST;
case 7:
return BlockFace.SOUTH_SOUTH_EAST;
case 8:
return BlockFace.SOUTH;
case 9:
return BlockFace.SOUTH_SOUTH_WEST;
case 10:
return BlockFace.SOUTH_WEST;
case 11:
return BlockFace.WEST_SOUTH_WEST;
case 12:
return BlockFace.WEST;
case 13:
return BlockFace.WEST_NORTH_WEST;
case 14:
return BlockFace.NORTH_WEST;
case 15:
return BlockFace.NORTH_NORTH_WEST;
default:
throw new IllegalArgumentException();
}
return switch(FastMath.floorMod(r, 16)) {
case 0 -> BlockFace.NORTH;
case 1 -> BlockFace.NORTH_NORTH_EAST;
case 2 -> BlockFace.NORTH_EAST;
case 3 -> BlockFace.EAST_NORTH_EAST;
case 4 -> BlockFace.EAST;
case 5 -> BlockFace.EAST_SOUTH_EAST;
case 6 -> BlockFace.SOUTH_EAST;
case 7 -> BlockFace.SOUTH_SOUTH_EAST;
case 8 -> BlockFace.SOUTH;
case 9 -> BlockFace.SOUTH_SOUTH_WEST;
case 10 -> BlockFace.SOUTH_WEST;
case 11 -> BlockFace.WEST_SOUTH_WEST;
case 12 -> BlockFace.WEST;
case 13 -> BlockFace.WEST_NORTH_WEST;
case 14 -> BlockFace.NORTH_WEST;
case 15 -> BlockFace.NORTH_NORTH_WEST;
default -> throw new IllegalArgumentException();
};
}
public static Axis getRotatedAxis(Axis orig, Rotation r) {
@@ -174,78 +134,45 @@ public class RotationUtil {
*/
@SuppressWarnings("fallthrough")
public static Rail.Shape getRotatedRail(Rail.Shape orig, Rotation r) {
switch(r) {
case CCW_90:
switch(orig) {
case NORTH_WEST:
return Rail.Shape.SOUTH_WEST;
case NORTH_SOUTH:
return Rail.Shape.EAST_WEST;
case SOUTH_WEST:
return Rail.Shape.SOUTH_EAST;
case SOUTH_EAST:
return Rail.Shape.NORTH_EAST;
case EAST_WEST:
return Rail.Shape.NORTH_SOUTH;
case NORTH_EAST:
return Rail.Shape.NORTH_WEST;
case ASCENDING_EAST:
return Rail.Shape.ASCENDING_NORTH;
case ASCENDING_WEST:
return Rail.Shape.ASCENDING_SOUTH;
case ASCENDING_NORTH:
return Rail.Shape.ASCENDING_WEST;
case ASCENDING_SOUTH:
return Rail.Shape.ASCENDING_EAST;
}
case CW_90:
switch(orig) {
case NORTH_WEST:
return Rail.Shape.NORTH_EAST;
case NORTH_SOUTH:
return Rail.Shape.EAST_WEST;
case SOUTH_WEST:
return Rail.Shape.NORTH_WEST;
case SOUTH_EAST:
return Rail.Shape.SOUTH_WEST;
case EAST_WEST:
return Rail.Shape.NORTH_SOUTH;
case NORTH_EAST:
return Rail.Shape.SOUTH_EAST;
case ASCENDING_EAST:
return Rail.Shape.ASCENDING_SOUTH;
case ASCENDING_WEST:
return Rail.Shape.ASCENDING_NORTH;
case ASCENDING_NORTH:
return Rail.Shape.ASCENDING_EAST;
case ASCENDING_SOUTH:
return Rail.Shape.ASCENDING_WEST;
}
case CW_180:
switch(orig) {
case NORTH_WEST:
return Rail.Shape.SOUTH_EAST;
case NORTH_SOUTH:
return Rail.Shape.NORTH_SOUTH;
case SOUTH_WEST:
return Rail.Shape.NORTH_EAST;
case SOUTH_EAST:
return Rail.Shape.NORTH_WEST;
case EAST_WEST:
return Rail.Shape.EAST_WEST;
case NORTH_EAST:
return Rail.Shape.SOUTH_WEST;
case ASCENDING_EAST:
return Rail.Shape.ASCENDING_WEST;
case ASCENDING_WEST:
return Rail.Shape.ASCENDING_EAST;
case ASCENDING_NORTH:
return Rail.Shape.ASCENDING_SOUTH;
case ASCENDING_SOUTH:
return Rail.Shape.ASCENDING_NORTH;
}
}
return orig;
return switch(r) {
case CCW_90 -> switch(orig) {
case NORTH_WEST -> Rail.Shape.SOUTH_WEST;
case NORTH_SOUTH -> Rail.Shape.EAST_WEST;
case SOUTH_WEST -> Rail.Shape.SOUTH_EAST;
case SOUTH_EAST -> Rail.Shape.NORTH_EAST;
case EAST_WEST -> Rail.Shape.NORTH_SOUTH;
case NORTH_EAST -> Rail.Shape.NORTH_WEST;
case ASCENDING_EAST -> Rail.Shape.ASCENDING_NORTH;
case ASCENDING_WEST -> Rail.Shape.ASCENDING_SOUTH;
case ASCENDING_NORTH -> Rail.Shape.ASCENDING_WEST;
case ASCENDING_SOUTH -> Rail.Shape.ASCENDING_EAST;
};
case CW_90 -> switch(orig) {
case NORTH_WEST -> Rail.Shape.NORTH_EAST;
case NORTH_SOUTH -> Rail.Shape.EAST_WEST;
case SOUTH_WEST -> Rail.Shape.NORTH_WEST;
case SOUTH_EAST -> Rail.Shape.SOUTH_WEST;
case EAST_WEST -> Rail.Shape.NORTH_SOUTH;
case NORTH_EAST -> Rail.Shape.SOUTH_EAST;
case ASCENDING_EAST -> Rail.Shape.ASCENDING_SOUTH;
case ASCENDING_WEST -> Rail.Shape.ASCENDING_NORTH;
case ASCENDING_NORTH -> Rail.Shape.ASCENDING_EAST;
case ASCENDING_SOUTH -> Rail.Shape.ASCENDING_WEST;
};
case CW_180 -> switch(orig) {
case NORTH_WEST -> Rail.Shape.SOUTH_EAST;
case NORTH_SOUTH -> Rail.Shape.NORTH_SOUTH;
case SOUTH_WEST -> Rail.Shape.NORTH_EAST;
case SOUTH_EAST -> Rail.Shape.NORTH_WEST;
case EAST_WEST -> Rail.Shape.EAST_WEST;
case NORTH_EAST -> Rail.Shape.SOUTH_WEST;
case ASCENDING_EAST -> Rail.Shape.ASCENDING_WEST;
case ASCENDING_WEST -> Rail.Shape.ASCENDING_EAST;
case ASCENDING_NORTH -> Rail.Shape.ASCENDING_SOUTH;
case ASCENDING_SOUTH -> Rail.Shape.ASCENDING_NORTH;
};
default -> orig;
};
}
public static void rotateBlockData(BlockData data, Rotation r) {
@@ -19,6 +19,6 @@ public class BufferedEntity implements BufferedItem {
@Override
public void paste(Location origin) {
Entity entity = origin.clone().add(0.5, 0, 0.5).getWorld().spawnEntity(origin, type);
main.getEventManager().callEvent(new EntitySpawnEvent(main.getWorld(entity.getWorld()).getGenerator().getConfigPack(), entity, entity.getLocation()));
main.getEventManager().callEvent(new EntitySpawnEvent(entity.getWorld().getTerraGenerator().getConfigPack(), entity, entity.getLocation()));
}
}
@@ -32,7 +32,7 @@ public class BufferedLootApplication implements BufferedItem {
}
Container container = (Container) data;
LootPopulateEvent event = new LootPopulateEvent(block, container, table, main.getWorld(block.getLocation().getWorld()).getGenerator().getConfigPack(), structure);
LootPopulateEvent event = new LootPopulateEvent(block, container, table, block.getLocation().getWorld().getTerraGenerator().getConfigPack(), structure);
main.getEventManager().callEvent(event);
if(event.isCancelled()) return;
@@ -40,7 +40,7 @@ public class BufferedLootApplication implements BufferedItem {
data.update(false);
} catch(Exception e) {
main.logger().warning("Could not apply loot at " + origin + ": " + e.getMessage());
main.getDebugLogger().stack(e);
e.printStackTrace();
}
}
}
@@ -21,7 +21,7 @@ public class BufferedStateManipulator implements BufferedItem {
state.update(false);
} catch(Exception e) {
main.logger().warning("Could not apply BlockState at " + origin + ": " + e.getMessage());
main.getDebugLogger().stack(e);
e.printStackTrace();
}
}
}
@@ -53,6 +53,7 @@ public class Transformer<F, T> {
private final LinkedHashMap<Transform<F, T>, List<Validator<T>>> transforms = new LinkedHashMap<>();
@SafeVarargs
@SuppressWarnings("varargs")
public final Builder<F, T> addTransform(Transform<F, T> transform, Validator<T>... validators) {
transforms.put(transform, Arrays.asList(validators));
return this;
@@ -1,9 +1,13 @@
package com.dfsek.terra.api.util;
import com.dfsek.terra.api.TerraPlugin;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
@@ -32,4 +36,12 @@ public class JarUtil {
}
}
}
public static JarFile getJarFile() throws URISyntaxException, IOException {
return new JarFile(new File(getJarURL().toURI()));
}
public static URL getJarURL() {
return TerraPlugin.class.getProtectionDomain().getCodeSource().getLocation();
}
}
@@ -60,12 +60,8 @@ public class UserDefinedCarver extends Carver {
functions.forEach((id, noise) -> {
switch(noise.getDimensions()) {
case 2:
p.registerFunction(id, new NoiseFunction2(noise.apply(hash)));
break;
case 3:
p.registerFunction(id, new NoiseFunction3(noise.apply(hash)));
break;
case 2 -> p.registerFunction(id, new NoiseFunction2(noise.apply(hash)));
case 3 -> p.registerFunction(id, new NoiseFunction3(noise.apply(hash)));
}
});
@@ -4,16 +4,10 @@ import com.dfsek.terra.api.TerraPlugin;
import com.dfsek.terra.api.command.CommandTemplate;
import com.dfsek.terra.api.command.annotation.Command;
import com.dfsek.terra.api.command.annotation.type.DebugCommand;
import com.dfsek.terra.api.command.annotation.type.PlayerCommand;
import com.dfsek.terra.api.command.annotation.type.WorldCommand;
import com.dfsek.terra.api.injection.annotations.Inject;
import com.dfsek.terra.api.platform.CommandSender;
import com.dfsek.terra.api.platform.entity.Player;
import com.dfsek.terra.world.TerraWorld;
@Command
@WorldCommand
@PlayerCommand
@DebugCommand
public class ProfileQueryCommand implements CommandTemplate {
@Inject
@@ -21,8 +15,9 @@ public class ProfileQueryCommand implements CommandTemplate {
@Override
public void execute(CommandSender sender) {
Player player = (Player) sender;
TerraWorld world = main.getWorld(player.getWorld());
player.sendMessage(world.getProfiler().getResultsFormatted());
StringBuilder data = new StringBuilder("Terra Profiler data dump: \n");
main.getProfiler().getTimings().forEach((id, timings) -> data.append(id).append(": ").append(timings.toString()).append('\n'));
main.logger().info(data.toString());
sender.sendMessage("Profiler data dumped to console.");
}
}
@@ -4,16 +4,10 @@ import com.dfsek.terra.api.TerraPlugin;
import com.dfsek.terra.api.command.CommandTemplate;
import com.dfsek.terra.api.command.annotation.Command;
import com.dfsek.terra.api.command.annotation.type.DebugCommand;
import com.dfsek.terra.api.command.annotation.type.PlayerCommand;
import com.dfsek.terra.api.command.annotation.type.WorldCommand;
import com.dfsek.terra.api.injection.annotations.Inject;
import com.dfsek.terra.api.platform.CommandSender;
import com.dfsek.terra.api.platform.entity.Player;
import com.dfsek.terra.world.TerraWorld;
@Command
@WorldCommand
@PlayerCommand
@DebugCommand
public class ProfileResetCommand implements CommandTemplate {
@Inject
@@ -21,9 +15,7 @@ public class ProfileResetCommand implements CommandTemplate {
@Override
public void execute(CommandSender sender) {
Player player = (Player) sender;
TerraWorld world = main.getWorld(player.getWorld());
world.getProfiler().reset();
player.sendMessage("Profiler reset.");
main.getProfiler().reset();
sender.sendMessage("Profiler reset.");
}
}
@@ -4,16 +4,10 @@ import com.dfsek.terra.api.TerraPlugin;
import com.dfsek.terra.api.command.CommandTemplate;
import com.dfsek.terra.api.command.annotation.Command;
import com.dfsek.terra.api.command.annotation.type.DebugCommand;
import com.dfsek.terra.api.command.annotation.type.PlayerCommand;
import com.dfsek.terra.api.command.annotation.type.WorldCommand;
import com.dfsek.terra.api.injection.annotations.Inject;
import com.dfsek.terra.api.platform.CommandSender;
import com.dfsek.terra.api.platform.entity.Player;
import com.dfsek.terra.world.TerraWorld;
@Command
@WorldCommand
@PlayerCommand
@DebugCommand
public class ProfileStartCommand implements CommandTemplate {
@Inject
@@ -21,9 +15,7 @@ public class ProfileStartCommand implements CommandTemplate {
@Override
public void execute(CommandSender sender) {
Player player = (Player) sender;
TerraWorld world = main.getWorld(player.getWorld());
world.getProfiler().setProfiling(true);
player.sendMessage("Profiling enabled.");
main.getProfiler().start();
sender.sendMessage("Profiling enabled.");
}
}
@@ -4,16 +4,10 @@ import com.dfsek.terra.api.TerraPlugin;
import com.dfsek.terra.api.command.CommandTemplate;
import com.dfsek.terra.api.command.annotation.Command;
import com.dfsek.terra.api.command.annotation.type.DebugCommand;
import com.dfsek.terra.api.command.annotation.type.PlayerCommand;
import com.dfsek.terra.api.command.annotation.type.WorldCommand;
import com.dfsek.terra.api.injection.annotations.Inject;
import com.dfsek.terra.api.platform.CommandSender;
import com.dfsek.terra.api.platform.entity.Player;
import com.dfsek.terra.world.TerraWorld;
@Command
@WorldCommand
@PlayerCommand
@DebugCommand
public class ProfileStopCommand implements CommandTemplate {
@Inject
@@ -21,9 +15,7 @@ public class ProfileStopCommand implements CommandTemplate {
@Override
public void execute(CommandSender sender) {
Player player = (Player) sender;
TerraWorld world = main.getWorld(player.getWorld());
world.getProfiler().setProfiling(false);
player.sendMessage("Profiling disabled.");
main.getProfiler().stop();
sender.sendMessage("Profiling disabled.");
}
}
@@ -69,12 +69,12 @@ public class PluginConfig implements ConfigTemplate {
ConfigLoader loader = new ConfigLoader();
loader.load(this, file);
if(dumpDefaultConfig) { // Don't dump default config if already loaded.
try(JarFile jar = new JarFile(new File(TerraPlugin.class.getProtectionDomain().getCodeSource().getLocation().toURI()))) {
try(JarFile jar = main.getModJar()) {
JarUtil.copyResourcesToDirectory(jar, "packs", new File(main.getDataFolder(), "packs").toString());
} catch(IOException | URISyntaxException e) {
main.getDebugLogger().error("Failed to dump default config files!");
e.printStackTrace();
main.getDebugLogger().error("Report this to Terra!");
main.getDebugLogger().error("Either you're on Forge, or this is a bug. If it's the latter, report this to Terra!");
}
}
} catch(ConfigException | IOException e) {
@@ -9,9 +9,6 @@ import com.dfsek.terra.api.platform.world.World;
import com.dfsek.terra.api.platform.world.generator.ChunkGenerator;
import com.dfsek.terra.api.platform.world.generator.GeneratorWrapper;
import java.io.File;
import java.util.UUID;
public class DummyWorld implements World {
@Override
public Object getHandle() {
@@ -33,31 +30,11 @@ public class DummyWorld implements World {
return () -> (GeneratorWrapper) () -> null;
}
@Override
public String getName() {
return "DUMMY";
}
@Override
public UUID getUID() {
return UUID.randomUUID();
}
@Override
public boolean isChunkGenerated(int x, int z) {
return false;
}
@Override
public Chunk getChunkAt(int x, int z) {
throw new UnsupportedOperationException("Cannot get chunk in DummyWorld");
}
@Override
public File getWorldFolder() {
throw new UnsupportedOperationException("Cannot get folder of DummyWorld");
}
@Override
public Block getBlockAt(int x, int y, int z) {
throw new UnsupportedOperationException("Cannot get block in DummyWorld");
@@ -11,12 +11,9 @@ public class OreFactory implements ConfigFactory<OreTemplate, Ore> {
@Override
public Ore build(OreTemplate config, TerraPlugin main) {
BlockData m = config.getMaterial();
switch(config.getType()) {
case SPHERE:
return new DeformedSphereOre(m, config.getReplaceable(), config.doPhysics(), config.getDeform(), config.getDeformFrequency(), config.getSize(), main);
case VANILLA:
return new VanillaOre(m, config.getReplaceable(), config.doPhysics(), config.getSize(), main);
}
return null;
return switch(config.getType()) {
case SPHERE -> new DeformedSphereOre(m, config.getReplaceable(), config.doPhysics(), config.getDeform(), config.getDeformFrequency(), config.getSize(), main);
case VANILLA -> new VanillaOre(m, config.getReplaceable(), config.doPhysics(), config.getSize(), main);
};
}
}
@@ -1,5 +1,6 @@
package com.dfsek.terra.config.fileloaders;
import com.dfsek.tectonic.config.Configuration;
import com.dfsek.tectonic.exception.ConfigException;
import com.dfsek.terra.api.util.GlueList;
@@ -18,8 +19,12 @@ public abstract class Loader {
*
* @param consumer Something to do with the streams.
*/
public Loader then(ExceptionalConsumer<List<InputStream>> consumer) throws ConfigException {
consumer.accept(new GlueList<>(streams.values()));
public Loader then(ExceptionalConsumer<List<Configuration>> consumer) throws ConfigException {
List<Configuration> list = new GlueList<>();
streams.forEach((id, stream) -> {
list.add(new Configuration(stream, id));
});
consumer.accept(list);
return this;
}
@@ -17,7 +17,7 @@ public final class LangUtil {
public static void load(String langID, TerraPlugin main) {
Logger logger = main.logger();
File file = new File(main.getDataFolder(), "lang");
try(JarFile jar = new JarFile(new File(TerraPlugin.class.getProtectionDomain().getCodeSource().getLocation().toURI()))) {
try(JarFile jar = main.getModJar()) {
copyResourcesToDirectory(jar, "lang", file.toString());
} catch(IOException | URISyntaxException e) {
main.getDebugLogger().error("Failed to dump language files!");
@@ -18,7 +18,7 @@ public class OreHolderLoader implements TypeLoader<OreHolder> {
Map<String, Object> map = (Map<String, Object>) o;
for(Map.Entry<String, Object> entry : map.entrySet()) {
holder.add(configLoader.loadClass(Ore.class, entry.getKey()), (OreConfig) configLoader.loadType(OreConfig.class, entry.getValue()));
holder.add(configLoader.loadClass(Ore.class, entry.getKey()), configLoader.loadClass(OreConfig.class, entry.getValue()), entry.getKey());
}
return holder;
@@ -21,15 +21,10 @@ public class BiomeProviderBuilderLoader implements TypeLoader<BiomeProvider.Biom
public BiomeProvider.BiomeProviderBuilder load(Type t, Object c, ConfigLoader loader) throws LoadException { // TODO: clean this up
Map<String, Object> map = (Map<String, Object>) c;
switch(loader.loadClass(BiomeProvider.Type.class, map.get("type"))) {
case IMAGE:
return loader.loadClass(ImageProviderTemplate.class, map);
case PIPELINE:
return loader.loadClass(BiomePipelineTemplate.class, map);
case SINGLE:
return loader.loadClass(SingleBiomeProviderTemplate.class, map);
}
throw new LoadException("No such biome provider type: " + map.get("type"));
return switch(loader.loadClass(BiomeProvider.Type.class, map.get("type"))) {
case IMAGE -> loader.loadClass(ImageProviderTemplate.class, map);
case PIPELINE -> loader.loadClass(BiomePipelineTemplate.class, map);
case SINGLE -> loader.loadClass(SingleBiomeProviderTemplate.class, map);
};
}
}
@@ -38,20 +38,13 @@ public class StageBuilderLoader implements TypeLoader<StageSeeded> {
return loader.loadClass(ExpanderStageTemplate.class, mutator);
} else throw new LoadException("No such expander \"" + stageType + "\"");
} else if(entry.getKey().equals("mutate")) {
switch(loader.loadClass(MutatorStage.Type.class, mutator.get("type"))) {
case SMOOTH:
return loader.loadClass(SmoothMutatorTemplate.class, mutator);
case REPLACE:
return loader.loadClass(ReplaceMutatorTemplate.class, mutator);
case REPLACE_LIST:
return loader.loadClass(ReplaceListMutatorTemplate.class, mutator);
case BORDER:
return loader.loadClass(BorderMutatorTemplate.class, mutator);
case BORDER_LIST:
return loader.loadClass(BorderListMutatorTemplate.class, mutator);
default:
throw new LoadException("No such mutator type \"" + mutator.get("type"));
}
return switch(loader.loadClass(MutatorStage.Type.class, mutator.get("type"))) {
case SMOOTH -> loader.loadClass(SmoothMutatorTemplate.class, mutator);
case REPLACE -> loader.loadClass(ReplaceMutatorTemplate.class, mutator);
case REPLACE_LIST -> loader.loadClass(ReplaceListMutatorTemplate.class, mutator);
case BORDER -> loader.loadClass(BorderMutatorTemplate.class, mutator);
case BORDER_LIST -> loader.loadClass(BorderListMutatorTemplate.class, mutator);
};
}
throw new LoadException("No such mutator \"" + entry.getKey() + "\"");
}
@@ -237,13 +237,13 @@ public class ConfigPack implements LoaderRegistrar {
}).close();
loader
.open("carving", ".yml").then(streams -> buildAll(new CarverFactory(this), carverRegistry, abstractConfigLoader.load(streams, CarverTemplate::new), main)).close()
.open("palettes", ".yml").then(streams -> buildAll(new PaletteFactory(), paletteRegistry, abstractConfigLoader.load(streams, PaletteTemplate::new), main)).close()
.open("ores", ".yml").then(streams -> buildAll(new OreFactory(), oreRegistry, abstractConfigLoader.load(streams, OreTemplate::new), main)).close()
.open("structures/trees", ".yml").then(streams -> buildAll(new TreeFactory(), treeRegistry, abstractConfigLoader.load(streams, TreeTemplate::new), main)).close()
.open("structures/structures", ".yml").then(streams -> buildAll(new StructureFactory(), structureRegistry, abstractConfigLoader.load(streams, StructureTemplate::new), main)).close()
.open("flora", ".yml").then(streams -> buildAll(new FloraFactory(), floraRegistry, abstractConfigLoader.load(streams, FloraTemplate::new), main)).close()
.open("biomes", ".yml").then(streams -> buildAll(new BiomeFactory(this), biomeRegistry, abstractConfigLoader.load(streams, () -> new BiomeTemplate(this, main)), main)).close();
.open("carving", ".yml").then(configs -> buildAll(new CarverFactory(this), carverRegistry, abstractConfigLoader.loadConfigs(configs, CarverTemplate::new), main)).close()
.open("palettes", ".yml").then(configs -> buildAll(new PaletteFactory(), paletteRegistry, abstractConfigLoader.loadConfigs(configs, PaletteTemplate::new), main)).close()
.open("ores", ".yml").then(configs -> buildAll(new OreFactory(), oreRegistry, abstractConfigLoader.loadConfigs(configs, OreTemplate::new), main)).close()
.open("structures/trees", ".yml").then(configs -> buildAll(new TreeFactory(), treeRegistry, abstractConfigLoader.loadConfigs(configs, TreeTemplate::new), main)).close()
.open("structures/structures", ".yml").then(configs -> buildAll(new StructureFactory(), structureRegistry, abstractConfigLoader.loadConfigs(configs, StructureTemplate::new), main)).close()
.open("flora", ".yml").then(configs -> buildAll(new FloraFactory(), floraRegistry, abstractConfigLoader.loadConfigs(configs, FloraTemplate::new), main)).close()
.open("biomes", ".yml").then(configs -> buildAll(new BiomeFactory(this), biomeRegistry, abstractConfigLoader.loadConfigs(configs, () -> new BiomeTemplate(this, main)), main)).close();
main.getEventManager().callEvent(new ConfigPackPostLoadEvent(this));
main.logger().info("Loaded config pack \"" + template.getID() + "\" v" + template.getVersion() + " by " + template.getAuthor() + " in " + (System.nanoTime() - start) / 1000000D + "ms.");
@@ -1,36 +0,0 @@
package com.dfsek.terra.profiler;
/**
* Class to hold a profiler data value. Contains formatting method to highlight value based on desired range.
*/
public class DataHolder {
private final long desired;
private final DataType type;
private final double desiredRangePercent;
/**
* Constructs a DataHolder with a DataType and a desired value, including a percentage around the desired value considered acceptable
*
* @param type The type of data held in this instance.
* @param desired The desired value. This should be the average value of whatever is being measured.
* @param desiredRangePercent The percentage around the desired value to be considered acceptable.
*/
public DataHolder(DataType type, long desired, double desiredRangePercent) {
this.desired = desired;
this.type = type;
this.desiredRangePercent = desiredRangePercent;
}
/**
* Returns a String, formatted with Bungee ChatColors.<br>
* GREEN if the value is better than desired and outside of acceptable range.<br>
* YELLOW if the value is better or worse than desired, and within acceptable range.<br>
* RED if the value is worse than desired and outside of acceptable range.<br>
*
* @param data The data to format.
* @return String - The formatted data.
*/
public String getFormattedData(long data) {
return type.getFormatted(data);
}
}
@@ -1,24 +0,0 @@
package com.dfsek.terra.profiler;
import net.jafama.FastMath;
public enum DataType {
PERIOD_MILLISECONDS(Desire.LOW, 1000000, "ms"), PERIOD_NANOSECONDS(Desire.LOW, 1, "ns");
private final Desire desire;
private final long divisor;
private final String unit;
DataType(Desire d, long divisor, String unit) {
this.desire = d;
this.divisor = divisor;
this.unit = unit;
}
public String getFormatted(long value) {
return (double) FastMath.round(((double) value / divisor) * 100D) / 100D + unit;
}
public Desire getDesire() {
return desire;
}
}
@@ -1,10 +0,0 @@
package com.dfsek.terra.profiler;
/**
* Enum to represent the "goal" of a value, whether it is desirable for the value to be high (e.g. Frequency), or low (e.g. Period)
*/
public enum Desire {
LOW, HIGH
}
@@ -0,0 +1,24 @@
package com.dfsek.terra.profiler;
public class Frame {
private final String id;
private final long start;
public Frame(String id) {
this.id = id;
this.start = System.nanoTime();
}
public String getId() {
return id;
}
public long getStart() {
return start;
}
@Override
public String toString() {
return id;
}
}
@@ -1,87 +0,0 @@
package com.dfsek.terra.profiler;
import com.dfsek.terra.api.math.MathUtil;
import com.dfsek.terra.api.util.GlueList;
import net.jafama.FastMath;
import java.math.BigInteger;
import java.util.LinkedList;
import java.util.List;
/**
* Class to record and hold all data for a single type of measurement performed by the profiler.
*/
public class Measurement {
private final List<Long> measurements = new LinkedList<>();
private final long desirable;
private final DataType type;
private long min = Long.MAX_VALUE;
private long max = Long.MIN_VALUE;
/**
* Constructs a new Measurement with a desired value and DataType.
*
* @param desirable The desired value of the measurement.
* @param type The type of data the measurement is holding.
*/
public Measurement(long desirable, DataType type) {
this.desirable = desirable;
this.type = type;
}
public void record(long value) {
max = FastMath.max(value, max);
min = FastMath.min(value, min);
measurements.add(value);
}
public int size() {
return measurements.size();
}
public ProfileFuture beginMeasurement() {
ProfileFuture future = new ProfileFuture();
long current = System.nanoTime();
future.thenRun(() -> record(System.nanoTime() - current));
return future;
}
public void reset() {
min = Long.MAX_VALUE;
max = Long.MIN_VALUE;
measurements.clear();
}
public DataHolder getDataHolder() {
return new DataHolder(type, desirable, 0.25);
}
public long getMin() {
if(min == Long.MAX_VALUE) return 0;
return min;
}
public long getMax() {
if(max == Long.MIN_VALUE) return 0;
return max;
}
public long average() {
BigInteger running = BigInteger.valueOf(0);
List<Long> mTemp = new GlueList<>(measurements);
for(Long l : mTemp) {
running = running.add(BigInteger.valueOf(l));
}
if(measurements.size() == 0) return 0;
return running.divide(BigInteger.valueOf(measurements.size())).longValue();
}
public double getStdDev() {
return MathUtil.standardDeviation(new GlueList<>(measurements));
}
public int entries() {
return measurements.size();
}
}
@@ -0,0 +1,14 @@
package com.dfsek.terra.profiler;
public class ProfileFrame implements AutoCloseable {
private final Runnable action;
public ProfileFrame(Runnable action) {
this.action = action;
}
@Override
public void close() {
action.run();
}
}
@@ -1,18 +0,0 @@
package com.dfsek.terra.profiler;
import java.util.concurrent.CompletableFuture;
public class ProfileFuture extends CompletableFuture<Boolean> implements AutoCloseable {
public ProfileFuture() {
super();
}
public boolean complete() {
return super.complete(true);
}
@Override
public void close() {
this.complete();
}
}
@@ -0,0 +1,56 @@
package com.dfsek.terra.profiler;
import java.util.Map;
public interface Profiler {
/**
* Push a frame to this profiler.
*
* @param frame ID of frame.
*/
void push(String frame);
/**
* Pop a frame from this profiler.
*
* @param frame ID of frame. Must match ID
* at the top of the profiler stack.
*/
void pop(String frame);
/**
* Start profiling.
*/
void start();
/**
* Stop profiling.
*/
void stop();
/**
* Get the profiler data.
*
* @return Profiler data.
*/
Map<String, Timings> getTimings();
/**
* Return a {@link AutoCloseable} implementation that
* may be used in a try-with-resources statement for
* more intuitive profiling, with auto-push/pop.
*
* @param frame ID of frame.
* @return {@link AutoCloseable} implementation for use
* in try-with-resources.
*/
default ProfileFrame profile(String frame) {
push(frame);
return new ProfileFrame(() -> pop(frame));
}
/**
* Clear the profiler data.
*/
void reset();
}
@@ -0,0 +1,91 @@
package com.dfsek.terra.profiler;
import com.dfsek.terra.api.util.mutable.MutableInteger;
import com.dfsek.terra.profiler.exception.MalformedStackException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
public class ProfilerImpl implements Profiler {
private static final ThreadLocal<Stack<Frame>> THREAD_STACK = ThreadLocal.withInitial(Stack::new);
private static final ThreadLocal<Map<String, List<Long>>> TIMINGS = ThreadLocal.withInitial(HashMap::new);
private final List<Map<String, List<Long>>> accessibleThreadMaps = new ArrayList<>();
private volatile boolean running = false;
private static boolean instantiated = false;
private static final ThreadLocal<Boolean> SAFE = ThreadLocal.withInitial(() -> false);
private static final ThreadLocal<MutableInteger> STACK_SIZE = ThreadLocal.withInitial(() -> new MutableInteger(0));
public ProfilerImpl() {
if(instantiated) throw new IllegalStateException("Only one instance of Profiler may exist!");
instantiated = true;
}
@Override
public void push(String frame) {
STACK_SIZE.get().increment();
if(running && SAFE.get()) {
Stack<Frame> stack = THREAD_STACK.get();
stack.push(new Frame(stack.isEmpty() ? frame : stack.peek().getId() + "." + frame));
} else SAFE.set(false);
}
@Override
public void pop(String frame) {
MutableInteger size = STACK_SIZE.get();
size.decrement();
if(running && SAFE.get()) {
long time = System.nanoTime();
Stack<Frame> stack = THREAD_STACK.get();
Map<String, List<Long>> timingsMap = TIMINGS.get();
if(timingsMap.size() == 0) {
synchronized(accessibleThreadMaps) {
accessibleThreadMaps.add(timingsMap);
}
}
Frame top = stack.pop();
if((stack.size() != 0 && !top.getId().endsWith("." + frame)) || (stack.size() == 0 && !top.getId().equals(frame)))
throw new MalformedStackException("Expected " + frame + ", found " + top);
List<Long> timings = timingsMap.computeIfAbsent(top.getId(), id -> new ArrayList<>());
timings.add(time - top.getStart());
}
if(size.get() == 0) SAFE.set(true);
}
@Override
public void start() {
running = true;
}
@Override
public void stop() {
running = false;
}
@Override
public Map<String, Timings> getTimings() {
Map<String, Timings> map = new HashMap<>();
accessibleThreadMaps.forEach(smap -> smap.forEach((key, list) -> {
String[] keys = key.split("\\.");
Timings timings = map.computeIfAbsent(keys[0], id -> new Timings());
for(int i = 1; i < keys.length; i++) {
timings = timings.getSubItem(keys[i]);
}
list.forEach(timings::addTime);
}));
return map;
}
@Override
public void reset() {
accessibleThreadMaps.forEach(Map::clear);
}
}
@@ -0,0 +1,73 @@
package com.dfsek.terra.profiler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Timings {
private final Map<String, Timings> subItems = new HashMap<>();
private final List<Long> timings = new ArrayList<>();
public void addTime(long time) {
timings.add(time);
}
public List<Long> getTimings() {
return timings;
}
public double average() {
return (double) timings.stream().reduce(0L, Long::sum) / timings.size();
}
public long max() {
return timings.stream().mapToLong(Long::longValue).max().orElse(0L);
}
public long min() {
return timings.stream().mapToLong(Long::longValue).min().orElse(0L);
}
public double sum() {
return timings.stream().mapToDouble(Long::doubleValue).sum();
}
public Timings getSubItem(String id) {
return subItems.computeIfAbsent(id, s -> new Timings());
}
public String toString(int indent, Timings parent, Set<Integer> branches) {
StringBuilder builder = new StringBuilder();
builder.append((double) min() / 1000000).append("ms min / ").append(average() / 1000000).append("ms avg / ")
.append((double) max() / 1000000).append("ms max (").append(timings.size()).append(" samples, ")
.append((sum() / parent.sum()) * 100).append("% of parent)");
List<String> frames = new ArrayList<>();
Set<Integer> newBranches = new HashSet<>(branches);
newBranches.add(indent);
subItems.forEach((id, timings) -> frames.add(id + ": " + timings.toString(indent + 1, this, newBranches)));
for(int i = 0; i < frames.size(); i++) {
builder.append('\n');
for(int j = 0; j < indent; j++) {
if(branches.contains(j)) builder.append("");
else builder.append(" ");
}
if(i == frames.size() - 1 && !frames.get(i).contains("\n")) builder.append("└───");
else builder.append("├───");
builder.append(frames.get(i));
}
return builder.toString();
}
@Override
public String toString() {
return toString(1, this, Collections.emptySet());
}
}
@@ -1,85 +0,0 @@
package com.dfsek.terra.profiler;
import com.dfsek.terra.api.platform.world.World;
import com.dfsek.terra.world.TerraWorld;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import net.jafama.FastMath;
import java.util.Map;
public class WorldProfiler {
private final BiMap<String, Measurement> measures = HashBiMap.create();
private final World world;
private boolean isProfiling;
public WorldProfiler(World w) {
if(!TerraWorld.isTerraWorld(w))
throw new IllegalArgumentException("Attempted to instantiate profiler on non-Terra managed world!");
this.addMeasurement(new Measurement(2500000, DataType.PERIOD_MILLISECONDS), "TotalChunkGenTime")
.addMeasurement(new Measurement(1500000, DataType.PERIOD_MILLISECONDS), "FloraTime")
.addMeasurement(new Measurement(10000000, DataType.PERIOD_MILLISECONDS), "TreeTime")
.addMeasurement(new Measurement(1500000, DataType.PERIOD_MILLISECONDS), "OreTime")
.addMeasurement(new Measurement(5000000, DataType.PERIOD_MILLISECONDS), "CaveTime")
.addMeasurement(new Measurement(1500000, DataType.PERIOD_MILLISECONDS), "StructureTime");
isProfiling = false;
this.world = w;
}
public String getResultsFormatted() {
if(! isProfiling) return "Profiler is not currently running.";
StringBuilder result = new StringBuilder("Gaea World Profiler Results (Min / Avg / Max / Std Dev): \n");
for(Map.Entry<String, Measurement> e : measures.entrySet()) {
result
.append(e.getKey())
.append(": ")
.append(e.getValue().getDataHolder().getFormattedData(e.getValue().getMin()))
.append(" / ")
.append(e.getValue().getDataHolder().getFormattedData(e.getValue().average()))
.append(" / ")
.append(e.getValue().getDataHolder().getFormattedData(e.getValue().getMax()))
.append(" / ")
.append((double) FastMath.round((e.getValue().getStdDev() / 1000000) * 100D) / 100D)
.append("ms")
.append(" (x").append(e.getValue().size()).append(")\n");
}
return result.toString();
}
public void reset() {
for(Map.Entry<String, Measurement> e : measures.entrySet()) {
e.getValue().reset();
}
}
public com.dfsek.terra.profiler.WorldProfiler addMeasurement(Measurement m, String name) {
measures.put(name, m);
return this;
}
public void setMeasurement(String id, long value) {
if(isProfiling) measures.get(id).record(value);
}
public ProfileFuture measure(String id) {
if(isProfiling) return measures.get(id).beginMeasurement();
else return null;
}
public String getID(Measurement m) {
return measures.inverse().get(m);
}
public boolean isProfiling() {
return isProfiling;
}
public void setProfiling(boolean enabled) {
this.isProfiling = enabled;
}
public World getWorld() {
return world;
}
}
@@ -0,0 +1,17 @@
package com.dfsek.terra.profiler.exception;
public class MalformedStackException extends ProfilerException {
private static final long serialVersionUID = -3009539681021691054L;
public MalformedStackException(String message) {
super(message);
}
public MalformedStackException(String message, Throwable cause) {
super(message, cause);
}
public MalformedStackException(Throwable cause) {
super(cause);
}
}
@@ -0,0 +1,17 @@
package com.dfsek.terra.profiler.exception;
public class ProfilerException extends RuntimeException {
private static final long serialVersionUID = 8206737998791649002L;
public ProfilerException(String message) {
super(message);
}
public ProfilerException(String message, Throwable cause) {
super(message, cause);
}
public ProfilerException(Throwable cause) {
super(cause);
}
}
@@ -65,7 +65,9 @@ public class OpenRegistry<T> implements Registry<T> {
@Override
public T get(String identifier) {
return objects.get(identifier).getValue();
Entry<T> entry = objects.get(identifier);
if(entry == null) return null;
return entry.getValue();
}
@Override
@@ -68,10 +68,4 @@ public class FloraRegistry extends OpenRegistry<Flora> {
private BlockData data(String s) {
return main.getWorldHandle().createBlockData(s);
}
@Override
public Flora get(String identifier) {
return super.get(identifier);
}
}
@@ -13,7 +13,6 @@ import com.dfsek.terra.api.world.generation.TerraChunkGenerator;
import com.dfsek.terra.api.world.palette.Palette;
import com.dfsek.terra.config.pack.ConfigPack;
import com.dfsek.terra.config.pack.WorldConfig;
import com.dfsek.terra.profiler.WorldProfiler;
import com.dfsek.terra.world.generation.math.samplers.Sampler;
import net.jafama.FastMath;
@@ -21,33 +20,25 @@ public class TerraWorld {
private final BiomeProvider provider;
private final WorldConfig config;
private final boolean safe;
private final WorldProfiler profiler;
private final World world;
private final BlockData air;
public TerraWorld(World w, ConfigPack c, TerraPlugin main) {
if(!isTerraWorld(w)) throw new IllegalArgumentException("World " + w + " is not a Terra World!");
if(!w.isTerraWorld()) throw new IllegalArgumentException("World " + w + " is not a Terra World!");
this.world = w;
config = c.toWorldConfig(this);
this.provider = config.getProvider();
profiler = new WorldProfiler(w);
air = main.getWorldHandle().createBlockData("minecraft:air");
main.getEventManager().callEvent(new TerraWorldLoadEvent(this, c));
safe = true;
}
public static boolean isTerraWorld(World w) {
return w.getGenerator().getHandle() instanceof GeneratorWrapper;
}
public World getWorld() {
return world;
}
public TerraChunkGenerator getGenerator() {
return ((GeneratorWrapper) world.getGenerator().getHandle()).getHandle();
}
public BiomeProvider getBiomeProvider() {
return provider;
@@ -61,9 +52,6 @@ public class TerraWorld {
return safe;
}
public WorldProfiler getProfiler() {
return profiler;
}
/**
* Get a block at an ungenerated location
@@ -15,7 +15,7 @@ import com.dfsek.terra.api.world.generation.TerraChunkGenerator;
import com.dfsek.terra.api.world.palette.Palette;
import com.dfsek.terra.config.pack.ConfigPack;
import com.dfsek.terra.config.templates.BiomeTemplate;
import com.dfsek.terra.profiler.ProfileFuture;
import com.dfsek.terra.profiler.ProfileFrame;
import com.dfsek.terra.world.Carver;
import com.dfsek.terra.world.TerraWorld;
import com.dfsek.terra.world.carving.NoiseCarver;
@@ -94,7 +94,7 @@ public class DefaultChunkGenerator2D implements TerraChunkGenerator {
public ChunkData generateChunkData(@NotNull World world, Random random, int chunkX, int chunkZ, ChunkData chunk) {
TerraWorld tw = main.getWorld(world);
BiomeProvider grid = tw.getBiomeProvider();
try(ProfileFuture ignore = tw.getProfiler().measure("TotalChunkGenTime")) {
try(ProfileFrame ignore = main.getProfiler().profile("chunk_base_2d")) {
if(!tw.isSafe()) return chunk;
int xOrig = (chunkX << 4);
int zOrig = (chunkZ << 4);
@@ -23,7 +23,7 @@ import com.dfsek.terra.api.world.palette.Palette;
import com.dfsek.terra.api.world.palette.SinglePalette;
import com.dfsek.terra.config.pack.ConfigPack;
import com.dfsek.terra.config.templates.BiomeTemplate;
import com.dfsek.terra.profiler.ProfileFuture;
import com.dfsek.terra.profiler.ProfileFrame;
import com.dfsek.terra.world.Carver;
import com.dfsek.terra.world.TerraWorld;
import com.dfsek.terra.world.carving.NoiseCarver;
@@ -50,7 +50,6 @@ public class DefaultChunkGenerator3D implements TerraChunkGenerator {
private final Carver carver;
public DefaultChunkGenerator3D(ConfigPack c, TerraPlugin main) {
this.configPack = c;
this.main = main;
@@ -104,9 +103,10 @@ public class DefaultChunkGenerator3D implements TerraChunkGenerator {
@Override
@SuppressWarnings({"try"})
public ChunkData generateChunkData(@NotNull World world, Random random, int chunkX, int chunkZ, ChunkData chunk) {
TerraWorld tw = main.getWorld(world);
BiomeProvider grid = tw.getBiomeProvider();
try(ProfileFuture ignore = tw.getProfiler().measure("TotalChunkGenTime")) {
try(ProfileFrame ignore = main.getProfiler().profile("chunk_base_3d")) {
TerraWorld tw = main.getWorld(world);
BiomeProvider grid = tw.getBiomeProvider();
if(!tw.isSafe()) return chunk;
int xOrig = (chunkX << 4);
int zOrig = (chunkZ << 4);
@@ -120,7 +120,7 @@ public class DefaultChunkGenerator3D implements TerraChunkGenerator {
int cx = xOrig + x;
int cz = zOrig + z;
TerraBiome b = grid.getBiome(xOrig + x, zOrig + z);
TerraBiome b = grid.getBiome(cx, cz);
BiomeTemplate c = ((UserDefinedBiome) b).getConfig();
int sea = c.getSeaLevel();
@@ -227,17 +227,20 @@ public class DefaultChunkGenerator3D implements TerraChunkGenerator {
return false;
}
@SuppressWarnings({"try"})
static void biomes(@NotNull World world, int chunkX, int chunkZ, @NotNull BiomeGrid biome, TerraPlugin main) {
int xOrig = (chunkX << 4);
int zOrig = (chunkZ << 4);
BiomeProvider grid = main.getWorld(world).getBiomeProvider();
for(int x = 0; x < 4; x++) {
for(int z = 0; z < 4; z++) {
int cx = xOrig + (x << 2);
int cz = zOrig + (z << 2);
TerraBiome b = grid.getBiome(cx, cz);
try(ProfileFrame ignore = main.getProfiler().profile("biomes")) {
int xOrig = (chunkX << 4);
int zOrig = (chunkZ << 4);
BiomeProvider grid = main.getWorld(world).getBiomeProvider();
for(int x = 0; x < 4; x++) {
for(int z = 0; z < 4; z++) {
int cx = xOrig + (x << 2);
int cz = zOrig + (z << 2);
TerraBiome b = grid.getBiome(cx, cz);
biome.setBiome(cx, cz, b.getVanillaBiomes().get(b.getGenerator(world).getBiomeNoise(), cx, 0, cz));
biome.setBiome(cx, cz, b.getVanillaBiomes().get(b.getGenerator(world).getBiomeNoise(), cx, 0, cz));
}
}
}
}
@@ -25,7 +25,7 @@ public class SamplerCache {
public Sampler load(@NotNull Long key) {
int cx = (int) (key >> 32);
int cz = (int) key.longValue();
return world.getGenerator().createSampler(cx, cz, world.getBiomeProvider(), world.getWorld(), world.getConfig().getTemplate().getElevationBlend());
return world.getWorld().getTerraGenerator().createSampler(cx, cz, world.getBiomeProvider(), world.getWorld(), world.getConfig().getTemplate().getElevationBlend());
}
});
}
@@ -14,7 +14,7 @@ import com.dfsek.terra.api.world.generation.TerraBlockPopulator;
import com.dfsek.terra.carving.UserDefinedCarver;
import com.dfsek.terra.config.pack.WorldConfig;
import com.dfsek.terra.config.templates.CarverTemplate;
import com.dfsek.terra.profiler.ProfileFuture;
import com.dfsek.terra.profiler.ProfileFrame;
import com.dfsek.terra.world.TerraWorld;
import org.jetbrains.annotations.NotNull;
@@ -38,7 +38,7 @@ public class CavePopulator implements TerraBlockPopulator, Chunkified {
TerraWorld tw = main.getWorld(world);
WorldHandle handle = main.getWorldHandle();
BlockData AIR = handle.createBlockData("minecraft:air");
try(ProfileFuture ignored = tw.getProfiler().measure("CaveTime")) {
try(ProfileFrame ignore = main.getProfiler().profile("carving")) {
Random random = PopulationUtil.getRandom(chunk);
if(!tw.isSafe()) return;
WorldConfig config = tw.getConfig();
@@ -49,38 +49,40 @@ public class CavePopulator implements TerraBlockPopulator, Chunkified {
Map<Location, BlockData> shiftCandidate = new HashMap<>();
Set<Block> updateNeeded = new HashSet<>();
c.carve(chunk.getX(), chunk.getZ(), world, (v, type) -> {
Block b = chunk.getBlock(v.getBlockX(), v.getBlockY(), v.getBlockZ());
BlockData m = b.getBlockData();
BlockType re = m.getBlockType();
switch(type) {
case CENTER:
if(template.getInner().canReplace(re)) {
b.setBlockData(template.getInner().get(v.getBlockY()).get(random), false);
if(template.getUpdate().contains(re)) updateNeeded.add(b);
if(template.getShift().containsKey(re)) shiftCandidate.put(b.getLocation(), m);
}
break;
case WALL:
if(template.getOuter().canReplace(re)) {
b.setBlockData(template.getOuter().get(v.getBlockY()).get(random), false);
if(template.getUpdate().contains(re)) updateNeeded.add(b);
if(template.getShift().containsKey(re)) shiftCandidate.put(b.getLocation(), m);
}
break;
case TOP:
if(template.getTop().canReplace(re)) {
b.setBlockData(template.getTop().get(v.getBlockY()).get(random), false);
if(template.getUpdate().contains(re)) updateNeeded.add(b);
if(template.getShift().containsKey(re)) shiftCandidate.put(b.getLocation(), m);
}
break;
case BOTTOM:
if(template.getBottom().canReplace(re)) {
b.setBlockData(template.getBottom().get(v.getBlockY()).get(random), false);
if(template.getUpdate().contains(re)) updateNeeded.add(b);
if(template.getShift().containsKey(re)) shiftCandidate.put(b.getLocation(), m);
}
break;
try(ProfileFrame ignored = main.getProfiler().profile("carving:" + c.getConfig().getID())) {
Block b = chunk.getBlock(v.getBlockX(), v.getBlockY(), v.getBlockZ());
BlockData m = b.getBlockData();
BlockType re = m.getBlockType();
switch(type) {
case CENTER:
if(template.getInner().canReplace(re)) {
b.setBlockData(template.getInner().get(v.getBlockY()).get(random), false);
if(template.getUpdate().contains(re)) updateNeeded.add(b);
if(template.getShift().containsKey(re)) shiftCandidate.put(b.getLocation(), m);
}
break;
case WALL:
if(template.getOuter().canReplace(re)) {
b.setBlockData(template.getOuter().get(v.getBlockY()).get(random), false);
if(template.getUpdate().contains(re)) updateNeeded.add(b);
if(template.getShift().containsKey(re)) shiftCandidate.put(b.getLocation(), m);
}
break;
case TOP:
if(template.getTop().canReplace(re)) {
b.setBlockData(template.getTop().get(v.getBlockY()).get(random), false);
if(template.getUpdate().contains(re)) updateNeeded.add(b);
if(template.getShift().containsKey(re)) shiftCandidate.put(b.getLocation(), m);
}
break;
case BOTTOM:
if(template.getBottom().canReplace(re)) {
b.setBlockData(template.getBottom().get(v.getBlockY()).get(random), false);
if(template.getUpdate().contains(re)) updateNeeded.add(b);
if(template.getShift().containsKey(re)) shiftCandidate.put(b.getLocation(), m);
}
break;
}
}
});
for(Map.Entry<Location, BlockData> entry : shiftCandidate.entrySet()) {
@@ -93,7 +95,7 @@ public class CavePopulator implements TerraBlockPopulator, Chunkified {
if(template.getShift().get(entry.getValue().getBlockType()).contains(mut.getBlock().getBlockData().getBlockType())) {
mut.getBlock().setBlockData(shiftStorage.computeIfAbsent(entry.getValue().getBlockType(), BlockType::getDefaultData), false);
}
} catch(NullPointerException ignore) {
} catch(NullPointerException ignored) {
}
}
for(Block b : updateNeeded) {
@@ -8,7 +8,7 @@ import com.dfsek.terra.api.util.world.PopulationUtil;
import com.dfsek.terra.api.world.biome.UserDefinedBiome;
import com.dfsek.terra.api.world.biome.provider.BiomeProvider;
import com.dfsek.terra.api.world.generation.TerraBlockPopulator;
import com.dfsek.terra.profiler.ProfileFuture;
import com.dfsek.terra.profiler.ProfileFrame;
import com.dfsek.terra.world.TerraWorld;
import com.dfsek.terra.world.population.items.flora.FloraLayer;
import org.jetbrains.annotations.NotNull;
@@ -32,7 +32,7 @@ public class FloraPopulator implements TerraBlockPopulator {
@Override
public void populate(@NotNull World world, @NotNull Chunk chunk) {
TerraWorld tw = main.getWorld(world);
try(ProfileFuture ignored = tw.getProfiler().measure("FloraTime")) {
try(ProfileFrame ignore = main.getProfiler().profile("flora")) {
if(tw.getConfig().getTemplate().disableFlora()) return;
if(!tw.isSafe()) return;
@@ -10,7 +10,7 @@ import com.dfsek.terra.api.world.biome.TerraBiome;
import com.dfsek.terra.api.world.biome.UserDefinedBiome;
import com.dfsek.terra.api.world.generation.TerraBlockPopulator;
import com.dfsek.terra.config.templates.BiomeTemplate;
import com.dfsek.terra.profiler.ProfileFuture;
import com.dfsek.terra.profiler.ProfileFrame;
import com.dfsek.terra.world.TerraWorld;
import org.jetbrains.annotations.NotNull;
@@ -27,7 +27,7 @@ public class OrePopulator implements TerraBlockPopulator {
@Override
public void populate(@NotNull World world, @NotNull Chunk chunk) {
TerraWorld tw = main.getWorld(world);
try(ProfileFuture ignored = tw.getProfiler().measure("OreTime")) {
try(ProfileFrame ignore = main.getProfiler().profile("ore")) {
if(tw.getConfig().getTemplate().disableOres()) return;
if(!tw.isSafe()) return;
@@ -40,11 +40,13 @@ public class OrePopulator implements TerraBlockPopulator {
BiomeTemplate config = ((UserDefinedBiome) b).getConfig();
int finalCx = cx;
int finalCz = cz;
config.getOreHolder().forEach((ore, oreConfig) -> {
int amount = oreConfig.getAmount().get(random);
for(int i = 0; i < amount; i++) {
Vector3 location = new Vector3(random.nextInt(16) + 16 * finalCx, oreConfig.getHeight().get(random), random.nextInt(16) + 16 * finalCz);
ore.generate(location, chunk, random);
config.getOreHolder().forEach((id, orePair) -> {
try(ProfileFrame ignored = main.getProfiler().profile("ore:" + id)) {
int amount = orePair.getRight().getAmount().get(random);
for(int i = 0; i < amount; i++) {
Vector3 location = new Vector3(random.nextInt(16) + 16 * finalCx, orePair.getRight().getHeight().get(random), random.nextInt(16) + 16 * finalCz);
orePair.getLeft().generate(location, chunk, random);
}
}
});
}
@@ -11,9 +11,8 @@ import com.dfsek.terra.api.world.biome.UserDefinedBiome;
import com.dfsek.terra.api.world.biome.provider.BiomeProvider;
import com.dfsek.terra.api.world.generation.Chunkified;
import com.dfsek.terra.api.world.generation.TerraBlockPopulator;
import com.dfsek.terra.config.pack.ConfigPack;
import com.dfsek.terra.config.pack.WorldConfig;
import com.dfsek.terra.profiler.ProfileFuture;
import com.dfsek.terra.profiler.ProfileFrame;
import com.dfsek.terra.world.TerraWorld;
import com.dfsek.terra.world.population.items.TerraStructure;
import net.jafama.FastMath;
@@ -32,7 +31,7 @@ public class StructurePopulator implements TerraBlockPopulator, Chunkified {
@Override
public void populate(@NotNull World world, @NotNull Chunk chunk) {
TerraWorld tw = main.getWorld(world);
try(ProfileFuture ignored = tw.getProfiler().measure("StructureTime")) {
try(ProfileFrame ignore = main.getProfiler().profile("structure")) {
if(tw.getConfig().getTemplate().disableStructures()) return;
int cx = (chunk.getX() << 4);
@@ -8,7 +8,7 @@ import com.dfsek.terra.api.util.world.PopulationUtil;
import com.dfsek.terra.api.world.biome.UserDefinedBiome;
import com.dfsek.terra.api.world.biome.provider.BiomeProvider;
import com.dfsek.terra.api.world.generation.TerraBlockPopulator;
import com.dfsek.terra.profiler.ProfileFuture;
import com.dfsek.terra.profiler.ProfileFrame;
import com.dfsek.terra.world.TerraWorld;
import com.dfsek.terra.world.population.items.tree.TreeLayer;
import net.jafama.FastMath;
@@ -32,7 +32,7 @@ public class TreePopulator implements TerraBlockPopulator {
@SuppressWarnings("try")
public void populate(@NotNull World world, @NotNull Chunk chunk) {
TerraWorld tw = main.getWorld(world);
try(ProfileFuture ignored = tw.getProfiler().measure("TreeTime")) {
try(ProfileFrame ignore = main.getProfiler().profile("tree")) {
if(tw.getConfig().getTemplate().disableTrees()) return;
if(!tw.isSafe()) return;
@@ -42,8 +42,9 @@ public class TreePopulator implements TerraBlockPopulator {
for(int z = 0; z < 16; z += 2) {
UserDefinedBiome biome = (UserDefinedBiome) provider.getBiome((chunk.getX() << 4) + x, (chunk.getZ() << 4) + z);
for(TreeLayer layer : biome.getConfig().getTrees()) {
if(layer.getDensity() >= random.nextDouble() * 100)
if(layer.getDensity() >= random.nextDouble() * 100) {
layer.place(chunk, new Vector2(offset(random, x), offset(random, z)));
}
}
}
}
@@ -16,7 +16,6 @@ public abstract class Ore {
protected TerraPlugin main;
public Ore(BlockData material, MaterialSet replaceable, boolean applyGravity, TerraPlugin main) {
this.material = material;
this.replaceable = replaceable;
this.applyGravity = applyGravity;
@@ -1,6 +1,7 @@
package com.dfsek.terra.world.population.items.ores;
import com.dfsek.terra.api.util.GlueList;
import com.dfsek.terra.api.util.generic.pair.ImmutablePair;
import java.util.List;
import java.util.function.BiConsumer;
@@ -11,22 +12,24 @@ import java.util.function.BiConsumer;
public class OreHolder {
private final List<Entry> entries = new GlueList<>();
public void forEach(BiConsumer<Ore, OreConfig> consumer) {
entries.forEach(entry -> consumer.accept(entry.getOre(), entry.getConfig()));
public void forEach(BiConsumer<String, ImmutablePair<Ore, OreConfig>> consumer) {
entries.forEach(entry -> consumer.accept(entry.getId(), ImmutablePair.of(entry.getOre(), entry.getConfig())));
}
public OreHolder add(Ore ore, OreConfig config) {
entries.add(new Entry(ore, config));
public OreHolder add(Ore ore, OreConfig config, String id) {
entries.add(new Entry(ore, config, id));
return this;
}
private static final class Entry {
private final Ore ore;
private final OreConfig config;
private final String id;
private Entry(Ore ore, OreConfig config) {
private Entry(Ore ore, OreConfig config, String id) {
this.ore = ore;
this.config = config;
this.id = id;
}
public OreConfig getConfig() {
@@ -36,5 +39,9 @@ public class OreHolder {
public Ore getOre() {
return ore;
}
public String getId() {
return id;
}
}
}
+1 -2
View File
@@ -7,7 +7,6 @@ cache:
carver: 512
structure: 32
sampler: 128
master-disable:
caves: false
biome-provider: 32
script:
max-recursion: 1000
@@ -40,6 +40,7 @@ import com.dfsek.terra.config.loaders.config.sampler.NoiseSamplerBuilderLoader;
import com.dfsek.terra.config.pack.ConfigPack;
import com.dfsek.terra.config.templates.AbstractableTemplate;
import com.dfsek.terra.config.templates.BiomeTemplate;
import com.dfsek.terra.profiler.Profiler;
import com.dfsek.terra.registry.config.BiomeRegistry;
import com.dfsek.terra.registry.config.NoiseRegistry;
import com.dfsek.terra.world.TerraWorld;
@@ -137,6 +138,11 @@ public class DistributionTest {
return null;
}
@Override
public Profiler getProfiler() {
return null;
}
@Override
public void register(TypeRegistry registry) {
@@ -153,7 +159,7 @@ public class DistributionTest {
new GenericLoaders(MAIN).register(loader);
BiomeRegistry biomeRegistry = new BiomeRegistry();
folderLoader.open("biomes", ".yml").then(inputStreams -> ConfigPack.buildAll((template, main) -> template, biomeRegistry, loader.load(inputStreams, TestBiome::new), MAIN));
folderLoader.open("biomes", ".yml").then(inputStreams -> ConfigPack.buildAll((template, main) -> template, biomeRegistry, loader.loadConfigs(inputStreams, TestBiome::new), MAIN));
BiomeProviderTemplate template = new BiomeProviderTemplate();
ConfigLoader pipeLoader = new ConfigLoader()
+1 -1
View File
@@ -46,7 +46,7 @@ public class ImageTest {
OpenRegistry<TerraBiome> biomeRegistry = new OpenRegistry<TerraBiome>() {
};
folderLoader.open("biomes", ".yml").then(inputStreams -> ConfigPack.buildAll((template, main) -> template, biomeRegistry, loader.load(inputStreams, TestBiome::new), null));
folderLoader.open("biomes", ".yml").then(inputStreams -> ConfigPack.buildAll((template, main) -> template, biomeRegistry, loader.loadConfigs(inputStreams, TestBiome::new), null));
return new ImageBiomeProvider(biomeRegistry.entries(), ImageIO.read(ImageTest.class.getResourceAsStream("/map.jpg")), 1, ImageBiomeProvider.Align.CENTER);
}
@@ -0,0 +1,63 @@
package profiler;
import com.dfsek.terra.profiler.Profiler;
import com.dfsek.terra.profiler.ProfilerImpl;
public class ProfilerTest {
private static final Profiler PROFILER = new ProfilerImpl();
//@Test
public static void main(String... a) throws InterruptedException {
//PROFILER.start();
for(int i = 0; i < 1000; i++) {
doThing();
}
for(int i = 0; i < 100; i++) {
doThirdOtherThing();
}
for(int i = 0; i < 100; i++) {
doOtherThing();
}
PROFILER.stop();
PROFILER.push("thing");
PROFILER.push("thing2");
PROFILER.start();
PROFILER.pop("thing2");
PROFILER.pop("thing");
PROFILER.push("thing4");
PROFILER.pop("thing4");
PROFILER.getTimings().forEach((id, timings) -> {
System.out.println(id + ": " + timings.toString());
});
}
private static void doThing() throws InterruptedException {
PROFILER.push("thing");
Thread.sleep(1);
doOtherThing();
thing4();
PROFILER.pop("thing");
}
private static void doOtherThing() throws InterruptedException {
PROFILER.push("thing2");
Thread.sleep(2);
doThirdOtherThing();
thing4();
PROFILER.pop("thing2");
}
private static void doThirdOtherThing() throws InterruptedException {
PROFILER.push("thing3");
Thread.sleep(2);
PROFILER.pop("thing3");
}
private static void thing4() throws InterruptedException {
PROFILER.push("thing4");
Thread.sleep(2);
PROFILER.pop("thing4");
}
}
@@ -13,6 +13,7 @@ import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -20,7 +21,7 @@ import java.util.Map;
public class ParserTest {
@Test
public void parse() throws IOException, ParseException {
Parser parser = new Parser(IOUtils.toString(getClass().getResourceAsStream("/test.tesf")));
Parser parser = new Parser(IOUtils.toString(getClass().getResourceAsStream("/test.tesf"), Charset.defaultCharset()));
parser.registerFunction("test", new FunctionBuilder<Test1>() {
@Override
@@ -35,14 +36,11 @@ public class ParserTest {
@Override
public Returnable.ReturnType getArgument(int position) {
switch(position) {
case 0:
return Returnable.ReturnType.STRING;
case 1:
return Returnable.ReturnType.NUMBER;
default:
return null;
}
return switch(position) {
case 0 -> Returnable.ReturnType.STRING;
case 1 -> Returnable.ReturnType.NUMBER;
default -> null;
};
}
});
+15
View File
@@ -0,0 +1,15 @@
# Magic options for more perf
org.gradle.jvmargs=-Xmx2048M -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC
org.gradle.vfs.watch=true
kapt.use.worker.api=true
kapt.include.compile.classpath=false
org.gradle.parallel=true
org.gradle.caching=true
org.gradle.warning.mode=all
#org.gradle.logging.level=info
# Project information
terra.description=A fast, modern, extensible, platform-agnostic data-driven world generator
terra.source=https://github.com/PolyhedralDev/Terra
terra.issues=https://github.com/PolyhedralDev/Terra/issues
terra.wiki=https://github.com/PolyhedralDev/Terra/wiki
terra.license=GNU General Public License, version 3.0
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
org.gradle.jvmargs=-Xmx4096m
+2 -2
View File
@@ -70,8 +70,8 @@ fun installServer(dir: String) {
// Cloning test setup.
gitClone("https://github.com/PolyhedralDev/WorldGenTestServer")
// Copying plugins
Files.move(Paths.get("WorldGenTestServer/plugins"),
Paths.get("$testDir/$dir/plugins"),
Files.move(file("WorldGenTestServer/plugins").toPath(),
file("$testDir/$dir/plugins").toPath(),
StandardCopyOption.REPLACE_EXISTING)
// Copying config
val serverText = URL("https://raw.githubusercontent.com/PolyhedralDev/WorldGenTestServer/master/server.properties").readText()
@@ -34,12 +34,15 @@ import com.dfsek.terra.bukkit.listeners.SpigotListener;
import com.dfsek.terra.bukkit.listeners.TerraListener;
import com.dfsek.terra.bukkit.util.PaperUtil;
import com.dfsek.terra.bukkit.world.BukkitBiome;
import com.dfsek.terra.bukkit.world.BukkitWorld;
import com.dfsek.terra.commands.CommandUtil;
import com.dfsek.terra.config.GenericLoaders;
import com.dfsek.terra.config.PluginConfig;
import com.dfsek.terra.config.lang.LangUtil;
import com.dfsek.terra.config.lang.Language;
import com.dfsek.terra.config.pack.ConfigPack;
import com.dfsek.terra.profiler.Profiler;
import com.dfsek.terra.profiler.ProfilerImpl;
import com.dfsek.terra.registry.master.AddonRegistry;
import com.dfsek.terra.registry.master.ConfigRegistry;
import com.dfsek.terra.world.TerraWorld;
@@ -64,6 +67,8 @@ public class TerraBukkitPlugin extends JavaPlugin implements TerraPlugin {
private final Map<World, TerraWorld> worldMap = new HashMap<>();
private final Map<String, ConfigPack> worlds = new HashMap<>();
private final Profiler profiler = new ProfilerImpl();
private final ConfigRegistry registry = new ConfigRegistry();
private final CheckedRegistry<ConfigPack> checkedRegistry = new CheckedRegistry<>(registry);
@@ -141,6 +146,11 @@ public class TerraBukkitPlugin extends JavaPlugin implements TerraPlugin {
Bukkit.getScheduler().runTask(this, task);
}
@Override
public Profiler getProfiler() {
return profiler;
}
@Override
public void onDisable() {
BukkitChunkGeneratorWrapper.saveAll();
@@ -259,14 +269,15 @@ public class TerraBukkitPlugin extends JavaPlugin implements TerraPlugin {
return checkedRegistry;
}
public TerraWorld getWorld(World w) {
if(!TerraWorld.isTerraWorld(w))
public TerraWorld getWorld(World world) {
BukkitWorld w = (BukkitWorld) world;
if(!w.isTerraWorld())
throw new IllegalArgumentException("Not a Terra world! " + w.getGenerator());
if(!worlds.containsKey(w.getName())) {
getLogger().warning("Unexpected world load detected: \"" + w.getName() + "\"");
return new TerraWorld(w, ((TerraChunkGenerator) w.getGenerator().getHandle()).getConfigPack(), this);
}
return worldMap.computeIfAbsent(w, world -> new TerraWorld(w, worlds.get(w.getName()), this));
return worldMap.computeIfAbsent(w, w2 -> new TerraWorld(w, worlds.get(w.getName()), this));
}
@Override
@@ -3,19 +3,11 @@ package com.dfsek.terra.bukkit.generator;
import com.dfsek.terra.api.TerraPlugin;
import com.dfsek.terra.api.platform.world.Chunk;
import com.dfsek.terra.api.platform.world.generator.GeneratorWrapper;
import com.dfsek.terra.api.world.generation.TerraBlockPopulator;
import com.dfsek.terra.api.world.generation.TerraChunkGenerator;
import com.dfsek.terra.bukkit.population.PopulationManager;
import com.dfsek.terra.bukkit.world.BukkitAdapter;
import com.dfsek.terra.bukkit.world.BukkitBiomeGrid;
import com.dfsek.terra.profiler.DataType;
import com.dfsek.terra.profiler.Measurement;
import com.dfsek.terra.world.TerraWorld;
import com.dfsek.terra.world.population.CavePopulator;
import com.dfsek.terra.world.population.FloraPopulator;
import com.dfsek.terra.world.population.OrePopulator;
import com.dfsek.terra.world.population.StructurePopulator;
import com.dfsek.terra.world.population.TreePopulator;
import org.bukkit.World;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
@@ -24,13 +16,10 @@ import org.jetbrains.annotations.NotNull;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;
public class BukkitChunkGeneratorWrapper extends ChunkGenerator implements GeneratorWrapper {
@@ -63,7 +52,7 @@ public class BukkitChunkGeneratorWrapper extends ChunkGenerator implements Gener
}
public static synchronized void fixChunk(Chunk c) {
if(!TerraWorld.isTerraWorld(c.getWorld())) throw new IllegalArgumentException();
if(!c.getWorld().isTerraWorld()) throw new IllegalArgumentException();
popMap.get(c.getWorld()).checkNeighbors(c.getX(), c.getZ(), c.getWorld());
}
@@ -76,8 +65,6 @@ public class BukkitChunkGeneratorWrapper extends ChunkGenerator implements Gener
e.printStackTrace();
}
popMap.put(w, popMan);
main.getWorld(w).getProfiler().addMeasurement(new Measurement(15000000, DataType.PERIOD_MILLISECONDS), "PopulationManagerTime");
popMan.attachProfiler(main.getWorld(w).getProfiler());
needsLoad = false;
}
@@ -44,7 +44,7 @@ public class CommonListener implements Listener {
public void onSaplingGrow(StructureGrowEvent e) {
if(e.isCancelled()) return;
World bukkit = BukkitAdapter.adapt(e.getWorld());
if(!TerraWorld.isTerraWorld(bukkit)) return;
if(!bukkit.isTerraWorld()) return;
TerraWorld tw = main.getWorld(bukkit);
WorldConfig c = tw.getConfig();
if(c.getTemplate().isDisableSaplings()) return;
@@ -18,8 +18,7 @@ public class PaperListener implements Listener {
@EventHandler
public void onStructureLocate(StructureLocateEvent e) {
if(!TerraWorld.isTerraWorld(BukkitAdapter.adapt(e.getWorld()))) return;
e.setResult(null); // Assume no result.
if(!BukkitAdapter.adapt(e.getWorld()).isTerraWorld()) return;
String name = "minecraft:" + e.getType().getName();
main.getDebugLogger().info("Overriding structure location for \"" + name + "\"");
TerraWorld tw = main.getWorld(BukkitAdapter.adapt(e.getWorld()));
@@ -32,10 +31,8 @@ public class PaperListener implements Listener {
}, main);
finder.run(); // Do this synchronously.
} else {
main.logger().warning("No overrides are defined for \"" + name + "\"");
e.setResult(e.getOrigin());
main.logger().warning("No overrides are defined for \"" + name + "\". Locating this structure will NOT work properly!");
}
}
}
@@ -34,7 +34,7 @@ public class SpigotListener implements Listener {
Entity entity = e.getEntity();
if(e.getEntityType().equals(EntityType.ENDER_SIGNAL)) {
main.getDebugLogger().info("Detected Ender Signal...");
if(!TerraWorld.isTerraWorld(BukkitAdapter.adapt(e.getEntity().getWorld()))) return;
if(!BukkitAdapter.adapt(e.getEntity().getWorld()).isTerraWorld()) return;
TerraWorld tw = main.getWorld(BukkitAdapter.adapt(e.getEntity().getWorld()));
EnderSignal signal = (EnderSignal) entity;
TerraStructure config = tw.getConfig().getStructureRegistry().get(tw.getConfig().getTemplate().getLocatable().get("STRONGHOLD"));
@@ -53,7 +53,7 @@ public class SpigotListener implements Listener {
@EventHandler
public void onCartographerChange(VillagerAcquireTradeEvent e) {
if(!TerraWorld.isTerraWorld(BukkitAdapter.adapt(e.getEntity().getWorld()))) return;
if(!BukkitAdapter.adapt(e.getEntity().getWorld()).isTerraWorld()) return;
if(!(e.getEntity() instanceof Villager)) return;
if(((Villager) e.getEntity()).getProfession().equals(Villager.Profession.CARTOGRAPHER)) {
main.logger().severe("Prevented server crash by stopping Cartographer villager from spawning.");
@@ -65,7 +65,7 @@ public class SpigotListener implements Listener {
@EventHandler
public void onCartographerLevel(VillagerCareerChangeEvent e) {
if(!TerraWorld.isTerraWorld(BukkitAdapter.adapt(e.getEntity().getWorld()))) return;
if(!BukkitAdapter.adapt(e.getEntity().getWorld()).isTerraWorld()) return;
if(e.getProfession().equals(Villager.Profession.CARTOGRAPHER)) {
main.logger().severe("Prevented server crash by stopping Cartographer villager from spawning.");
main.logger().severe("Please upgrade to Paper, which has a StructureLocateEvent that fixes this issue");
@@ -2,6 +2,7 @@ package com.dfsek.terra.bukkit.population;
import com.dfsek.terra.api.platform.world.Chunk;
import com.dfsek.terra.bukkit.world.BukkitWorld;
import java.io.Serializable;
import java.util.UUID;
@@ -21,7 +22,7 @@ public class ChunkCoordinate implements Serializable {
public ChunkCoordinate(Chunk c) {
this.x = c.getX();
this.z = c.getZ();
this.worldID = c.getWorld().getUID();
this.worldID = ((BukkitWorld) c.getWorld()).getUID();
}
public UUID getWorldID() {
@@ -1,20 +0,0 @@
package com.dfsek.terra.bukkit.population;
import com.dfsek.terra.api.platform.world.World;
import java.io.File;
public class Gaea {
private static boolean debug;
public static File getGaeaFolder(World w) {
File f = new File(w.getWorldFolder(), "gaea");
f.mkdirs();
return f;
}
public static boolean isDebug() {
return debug;
}
}
@@ -5,12 +5,11 @@ import com.dfsek.terra.api.platform.world.Chunk;
import com.dfsek.terra.api.platform.world.World;
import com.dfsek.terra.api.util.FastRandom;
import com.dfsek.terra.api.world.generation.Chunkified;
import com.dfsek.terra.api.world.generation.TerraBlockPopulator;
import com.dfsek.terra.api.world.generation.TerraChunkGenerator;
import com.dfsek.terra.bukkit.TerraBukkitPlugin;
import com.dfsek.terra.bukkit.world.BukkitAdapter;
import com.dfsek.terra.profiler.ProfileFuture;
import com.dfsek.terra.profiler.WorldProfiler;
import com.dfsek.terra.bukkit.world.BukkitWorld;
import com.dfsek.terra.profiler.ProfileFrame;
import org.bukkit.generator.BlockPopulator;
import org.jetbrains.annotations.NotNull;
@@ -26,39 +25,36 @@ public class PopulationManager extends BlockPopulator {
private final TerraChunkGenerator generator;
private final HashSet<ChunkCoordinate> needsPop = new HashSet<>();
private final TerraPlugin main;
private WorldProfiler profiler;
public PopulationManager(TerraChunkGenerator generator, TerraPlugin main) {
this.generator = generator;
this.main = main;
}
private ProfileFuture measure() {
if(profiler != null) return profiler.measure("PopulationManagerTime");
return null;
}
public void attachProfiler(WorldProfiler p) {
this.profiler = p;
}
@SuppressWarnings("unchecked")
public synchronized void saveBlocks(World w) throws IOException {
File f = new File(Gaea.getGaeaFolder(w), "chunks.bin");
File f = new File(getDataFolder(w), "chunks.bin");
f.createNewFile();
SerializationUtil.toFile((HashSet<ChunkCoordinate>) needsPop.clone(), f);
}
@SuppressWarnings("unchecked")
public synchronized void loadBlocks(World w) throws IOException, ClassNotFoundException {
File f = new File(Gaea.getGaeaFolder(w), "chunks.bin");
File f = new File(getDataFolder(w), "chunks.bin");
needsPop.addAll((HashSet<ChunkCoordinate>) SerializationUtil.fromFile(f));
}
public static File getDataFolder(World w) {
File f = new File(((BukkitWorld) w).getWorldFolder(), "gaea");
f.mkdirs();
return f;
}
// Synchronize to prevent chunks from being queued for population multiple times.
public synchronized void checkNeighbors(int x, int z, World w) {
ChunkCoordinate c = new ChunkCoordinate(x, z, w.getUID());
public synchronized void checkNeighbors(int x, int z, World world) {
BukkitWorld w = (BukkitWorld) world;
ChunkCoordinate c = new ChunkCoordinate(x, z, (w).getUID());
if(w.isChunkGenerated(x + 1, z)
&& w.isChunkGenerated(x - 1, z)
&& w.isChunkGenerated(x, z + 1)
@@ -78,8 +74,9 @@ public class PopulationManager extends BlockPopulator {
}
@Override
@SuppressWarnings("try")
public void populate(org.bukkit.@NotNull World world, @NotNull Random random, org.bukkit.@NotNull Chunk source) {
try(ProfileFuture ignored = measure()) {
try(ProfileFrame ignore = main.getProfiler().profile("popman")) {
Chunk chunk = BukkitAdapter.adapt(source);
needsPop.add(new ChunkCoordinate(chunk));
int x = chunk.getX();
@@ -50,20 +50,13 @@ public final class BukkitAdapter {
public static Stairs.Shape adapt(org.bukkit.block.data.type.Stairs.Shape shape) {
switch(shape) {
case STRAIGHT:
return Stairs.Shape.STRAIGHT;
case INNER_LEFT:
return Stairs.Shape.INNER_LEFT;
case OUTER_LEFT:
return Stairs.Shape.OUTER_LEFT;
case INNER_RIGHT:
return Stairs.Shape.INNER_RIGHT;
case OUTER_RIGHT:
return Stairs.Shape.OUTER_RIGHT;
default:
throw new IllegalStateException();
}
return switch(shape) {
case STRAIGHT -> Stairs.Shape.STRAIGHT;
case INNER_LEFT -> Stairs.Shape.INNER_LEFT;
case OUTER_LEFT -> Stairs.Shape.OUTER_LEFT;
case INNER_RIGHT -> Stairs.Shape.INNER_RIGHT;
case OUTER_RIGHT -> Stairs.Shape.OUTER_RIGHT;
};
}
public static BlockData adapt(org.bukkit.block.data.BlockData data) {
@@ -75,265 +68,154 @@ public final class BukkitAdapter {
}
public static Axis adapt(org.bukkit.Axis axis) {
switch(axis) {
case X:
return Axis.X;
case Y:
return Axis.Y;
case Z:
return Axis.Z;
default:
throw new IllegalStateException();
}
return switch(axis) {
case X -> Axis.X;
case Y -> Axis.Y;
case Z -> Axis.Z;
};
}
public static Bisected.Half adapt(org.bukkit.block.data.Bisected.Half half) {
switch(half) {
case BOTTOM:
return Bisected.Half.BOTTOM;
case TOP:
return Bisected.Half.TOP;
default:
throw new IllegalStateException();
}
return switch(half) {
case BOTTOM -> Bisected.Half.BOTTOM;
case TOP -> Bisected.Half.TOP;
};
}
public static BlockFace adapt(org.bukkit.block.BlockFace face) {
switch(face) {
case DOWN:
return BlockFace.DOWN;
case UP:
return BlockFace.UP;
case NORTH_WEST:
return BlockFace.NORTH_WEST;
case NORTH_EAST:
return BlockFace.NORTH_EAST;
case SOUTH_EAST:
return BlockFace.SOUTH_EAST;
case SOUTH_WEST:
return BlockFace.SOUTH_WEST;
case NORTH_NORTH_WEST:
return BlockFace.NORTH_NORTH_WEST;
case WEST_NORTH_WEST:
return BlockFace.WEST_NORTH_WEST;
case WEST_SOUTH_WEST:
return BlockFace.WEST_SOUTH_WEST;
case SOUTH_SOUTH_WEST:
return BlockFace.SOUTH_SOUTH_WEST;
case EAST_NORTH_EAST:
return BlockFace.EAST_NORTH_EAST;
case WEST:
return BlockFace.WEST;
case SOUTH:
return BlockFace.SOUTH;
case EAST:
return BlockFace.EAST;
case NORTH:
return BlockFace.NORTH;
case SELF:
return BlockFace.SELF;
case EAST_SOUTH_EAST:
return BlockFace.EAST_SOUTH_EAST;
case NORTH_NORTH_EAST:
return BlockFace.NORTH_NORTH_EAST;
case SOUTH_SOUTH_EAST:
return BlockFace.SOUTH_SOUTH_EAST;
default:
throw new IllegalStateException();
}
return switch(face) {
case DOWN -> BlockFace.DOWN;
case UP -> BlockFace.UP;
case NORTH_WEST -> BlockFace.NORTH_WEST;
case NORTH_EAST -> BlockFace.NORTH_EAST;
case SOUTH_EAST -> BlockFace.SOUTH_EAST;
case SOUTH_WEST -> BlockFace.SOUTH_WEST;
case NORTH_NORTH_WEST -> BlockFace.NORTH_NORTH_WEST;
case WEST_NORTH_WEST -> BlockFace.WEST_NORTH_WEST;
case WEST_SOUTH_WEST -> BlockFace.WEST_SOUTH_WEST;
case SOUTH_SOUTH_WEST -> BlockFace.SOUTH_SOUTH_WEST;
case EAST_NORTH_EAST -> BlockFace.EAST_NORTH_EAST;
case WEST -> BlockFace.WEST;
case SOUTH -> BlockFace.SOUTH;
case EAST -> BlockFace.EAST;
case NORTH -> BlockFace.NORTH;
case SELF -> BlockFace.SELF;
case EAST_SOUTH_EAST -> BlockFace.EAST_SOUTH_EAST;
case NORTH_NORTH_EAST -> BlockFace.NORTH_NORTH_EAST;
case SOUTH_SOUTH_EAST -> BlockFace.SOUTH_SOUTH_EAST;
};
}
public static Slab.Type adapt(org.bukkit.block.data.type.Slab.Type type) {
switch(type) {
case BOTTOM:
return Slab.Type.BOTTOM;
case TOP:
return Slab.Type.TOP;
case DOUBLE:
return Slab.Type.DOUBLE;
default:
throw new IllegalStateException();
}
return switch(type) {
case BOTTOM -> Slab.Type.BOTTOM;
case TOP -> Slab.Type.TOP;
case DOUBLE -> Slab.Type.DOUBLE;
};
}
public static RedstoneWire.Connection adapt(org.bukkit.block.data.type.RedstoneWire.Connection connection) {
switch(connection) {
case NONE:
return RedstoneWire.Connection.NONE;
case UP:
return RedstoneWire.Connection.UP;
case SIDE:
return RedstoneWire.Connection.SIDE;
default:
throw new IllegalStateException();
}
return switch(connection) {
case NONE -> RedstoneWire.Connection.NONE;
case UP -> RedstoneWire.Connection.UP;
case SIDE -> RedstoneWire.Connection.SIDE;
};
}
public static org.bukkit.block.data.type.RedstoneWire.Connection adapt(RedstoneWire.Connection connection) {
switch(connection) {
case SIDE:
return org.bukkit.block.data.type.RedstoneWire.Connection.SIDE;
case UP:
return org.bukkit.block.data.type.RedstoneWire.Connection.UP;
case NONE:
return org.bukkit.block.data.type.RedstoneWire.Connection.NONE;
default:
throw new IllegalStateException();
}
return switch(connection) {
case SIDE -> org.bukkit.block.data.type.RedstoneWire.Connection.SIDE;
case UP -> org.bukkit.block.data.type.RedstoneWire.Connection.UP;
case NONE -> org.bukkit.block.data.type.RedstoneWire.Connection.NONE;
};
}
public static org.bukkit.block.data.type.Stairs.Shape adapt(Stairs.Shape shape) {
switch(shape) {
case STRAIGHT:
return org.bukkit.block.data.type.Stairs.Shape.STRAIGHT;
case INNER_LEFT:
return org.bukkit.block.data.type.Stairs.Shape.INNER_LEFT;
case OUTER_LEFT:
return org.bukkit.block.data.type.Stairs.Shape.OUTER_LEFT;
case INNER_RIGHT:
return org.bukkit.block.data.type.Stairs.Shape.INNER_RIGHT;
case OUTER_RIGHT:
return org.bukkit.block.data.type.Stairs.Shape.OUTER_RIGHT;
default:
throw new IllegalStateException();
}
return switch(shape) {
case STRAIGHT -> org.bukkit.block.data.type.Stairs.Shape.STRAIGHT;
case INNER_LEFT -> org.bukkit.block.data.type.Stairs.Shape.INNER_LEFT;
case OUTER_LEFT -> org.bukkit.block.data.type.Stairs.Shape.OUTER_LEFT;
case INNER_RIGHT -> org.bukkit.block.data.type.Stairs.Shape.INNER_RIGHT;
case OUTER_RIGHT -> org.bukkit.block.data.type.Stairs.Shape.OUTER_RIGHT;
};
}
public static Rail.Shape adapt(org.bukkit.block.data.Rail.Shape shape) {
switch(shape) {
case SOUTH_WEST:
return Rail.Shape.SOUTH_WEST;
case SOUTH_EAST:
return Rail.Shape.SOUTH_EAST;
case NORTH_EAST:
return Rail.Shape.NORTH_EAST;
case NORTH_WEST:
return Rail.Shape.NORTH_WEST;
case ASCENDING_EAST:
return Rail.Shape.ASCENDING_EAST;
case ASCENDING_WEST:
return Rail.Shape.ASCENDING_WEST;
case ASCENDING_SOUTH:
return Rail.Shape.ASCENDING_SOUTH;
case ASCENDING_NORTH:
return Rail.Shape.ASCENDING_NORTH;
case NORTH_SOUTH:
return Rail.Shape.NORTH_SOUTH;
case EAST_WEST:
return Rail.Shape.EAST_WEST;
default:
throw new IllegalStateException();
}
return switch(shape) {
case SOUTH_WEST -> Rail.Shape.SOUTH_WEST;
case SOUTH_EAST -> Rail.Shape.SOUTH_EAST;
case NORTH_EAST -> Rail.Shape.NORTH_EAST;
case NORTH_WEST -> Rail.Shape.NORTH_WEST;
case ASCENDING_EAST -> Rail.Shape.ASCENDING_EAST;
case ASCENDING_WEST -> Rail.Shape.ASCENDING_WEST;
case ASCENDING_SOUTH -> Rail.Shape.ASCENDING_SOUTH;
case ASCENDING_NORTH -> Rail.Shape.ASCENDING_NORTH;
case NORTH_SOUTH -> Rail.Shape.NORTH_SOUTH;
case EAST_WEST -> Rail.Shape.EAST_WEST;
};
}
public static org.bukkit.block.data.Rail.Shape adapt(Rail.Shape shape) {
switch(shape) {
case EAST_WEST:
return org.bukkit.block.data.Rail.Shape.EAST_WEST;
case NORTH_SOUTH:
return org.bukkit.block.data.Rail.Shape.NORTH_SOUTH;
case ASCENDING_NORTH:
return org.bukkit.block.data.Rail.Shape.ASCENDING_NORTH;
case ASCENDING_SOUTH:
return org.bukkit.block.data.Rail.Shape.ASCENDING_SOUTH;
case ASCENDING_WEST:
return org.bukkit.block.data.Rail.Shape.ASCENDING_WEST;
case ASCENDING_EAST:
return org.bukkit.block.data.Rail.Shape.ASCENDING_EAST;
case NORTH_WEST:
return org.bukkit.block.data.Rail.Shape.NORTH_WEST;
case NORTH_EAST:
return org.bukkit.block.data.Rail.Shape.NORTH_EAST;
case SOUTH_EAST:
return org.bukkit.block.data.Rail.Shape.SOUTH_EAST;
case SOUTH_WEST:
return org.bukkit.block.data.Rail.Shape.SOUTH_WEST;
default:
throw new IllegalStateException();
}
return switch(shape) {
case EAST_WEST -> org.bukkit.block.data.Rail.Shape.EAST_WEST;
case NORTH_SOUTH -> org.bukkit.block.data.Rail.Shape.NORTH_SOUTH;
case ASCENDING_NORTH -> org.bukkit.block.data.Rail.Shape.ASCENDING_NORTH;
case ASCENDING_SOUTH -> org.bukkit.block.data.Rail.Shape.ASCENDING_SOUTH;
case ASCENDING_WEST -> org.bukkit.block.data.Rail.Shape.ASCENDING_WEST;
case ASCENDING_EAST -> org.bukkit.block.data.Rail.Shape.ASCENDING_EAST;
case NORTH_WEST -> org.bukkit.block.data.Rail.Shape.NORTH_WEST;
case NORTH_EAST -> org.bukkit.block.data.Rail.Shape.NORTH_EAST;
case SOUTH_EAST -> org.bukkit.block.data.Rail.Shape.SOUTH_EAST;
case SOUTH_WEST -> org.bukkit.block.data.Rail.Shape.SOUTH_WEST;
};
}
public static org.bukkit.block.data.Bisected.Half adapt(Bisected.Half half) {
switch(half) {
case TOP:
return org.bukkit.block.data.Bisected.Half.TOP;
case BOTTOM:
return org.bukkit.block.data.Bisected.Half.BOTTOM;
default:
throw new IllegalStateException();
}
return switch(half) {
case TOP -> org.bukkit.block.data.Bisected.Half.TOP;
case BOTTOM -> org.bukkit.block.data.Bisected.Half.BOTTOM;
};
}
public static org.bukkit.Axis adapt(Axis axis) {
switch(axis) {
case Z:
return org.bukkit.Axis.Z;
case Y:
return org.bukkit.Axis.Y;
case X:
return org.bukkit.Axis.X;
default:
throw new IllegalStateException();
}
return switch(axis) {
case Z -> org.bukkit.Axis.Z;
case Y -> org.bukkit.Axis.Y;
case X -> org.bukkit.Axis.X;
};
}
public static org.bukkit.block.BlockFace adapt(BlockFace face) {
switch(face) {
case DOWN:
return org.bukkit.block.BlockFace.DOWN;
case UP:
return org.bukkit.block.BlockFace.UP;
case NORTH_WEST:
return org.bukkit.block.BlockFace.NORTH_WEST;
case NORTH_EAST:
return org.bukkit.block.BlockFace.NORTH_EAST;
case SOUTH_EAST:
return org.bukkit.block.BlockFace.SOUTH_EAST;
case SOUTH_WEST:
return org.bukkit.block.BlockFace.SOUTH_WEST;
case NORTH_NORTH_WEST:
return org.bukkit.block.BlockFace.NORTH_NORTH_WEST;
case WEST_NORTH_WEST:
return org.bukkit.block.BlockFace.WEST_NORTH_WEST;
case WEST_SOUTH_WEST:
return org.bukkit.block.BlockFace.WEST_SOUTH_WEST;
case SOUTH_SOUTH_WEST:
return org.bukkit.block.BlockFace.SOUTH_SOUTH_WEST;
case EAST_NORTH_EAST:
return org.bukkit.block.BlockFace.EAST_NORTH_EAST;
case WEST:
return org.bukkit.block.BlockFace.WEST;
case SOUTH:
return org.bukkit.block.BlockFace.SOUTH;
case EAST:
return org.bukkit.block.BlockFace.EAST;
case NORTH:
return org.bukkit.block.BlockFace.NORTH;
case SELF:
return org.bukkit.block.BlockFace.SELF;
case EAST_SOUTH_EAST:
return org.bukkit.block.BlockFace.EAST_SOUTH_EAST;
case NORTH_NORTH_EAST:
return org.bukkit.block.BlockFace.NORTH_NORTH_EAST;
case SOUTH_SOUTH_EAST:
return org.bukkit.block.BlockFace.SOUTH_SOUTH_EAST;
default:
throw new IllegalStateException();
}
return switch(face) {
case DOWN -> org.bukkit.block.BlockFace.DOWN;
case UP -> org.bukkit.block.BlockFace.UP;
case NORTH_WEST -> org.bukkit.block.BlockFace.NORTH_WEST;
case NORTH_EAST -> org.bukkit.block.BlockFace.NORTH_EAST;
case SOUTH_EAST -> org.bukkit.block.BlockFace.SOUTH_EAST;
case SOUTH_WEST -> org.bukkit.block.BlockFace.SOUTH_WEST;
case NORTH_NORTH_WEST -> org.bukkit.block.BlockFace.NORTH_NORTH_WEST;
case WEST_NORTH_WEST -> org.bukkit.block.BlockFace.WEST_NORTH_WEST;
case WEST_SOUTH_WEST -> org.bukkit.block.BlockFace.WEST_SOUTH_WEST;
case SOUTH_SOUTH_WEST -> org.bukkit.block.BlockFace.SOUTH_SOUTH_WEST;
case EAST_NORTH_EAST -> org.bukkit.block.BlockFace.EAST_NORTH_EAST;
case WEST -> org.bukkit.block.BlockFace.WEST;
case SOUTH -> org.bukkit.block.BlockFace.SOUTH;
case EAST -> org.bukkit.block.BlockFace.EAST;
case NORTH -> org.bukkit.block.BlockFace.NORTH;
case SELF -> org.bukkit.block.BlockFace.SELF;
case EAST_SOUTH_EAST -> org.bukkit.block.BlockFace.EAST_SOUTH_EAST;
case NORTH_NORTH_EAST -> org.bukkit.block.BlockFace.NORTH_NORTH_EAST;
case SOUTH_SOUTH_EAST -> org.bukkit.block.BlockFace.SOUTH_SOUTH_EAST;
};
}
public static org.bukkit.block.data.type.Slab.Type adapt(Slab.Type type) {
switch(type) {
case TOP:
return org.bukkit.block.data.type.Slab.Type.TOP;
case DOUBLE:
return org.bukkit.block.data.type.Slab.Type.DOUBLE;
case BOTTOM:
return org.bukkit.block.data.type.Slab.Type.BOTTOM;
default:
throw new IllegalStateException();
}
return switch(type) {
case TOP -> org.bukkit.block.data.type.Slab.Type.TOP;
case DOUBLE -> org.bukkit.block.data.type.Slab.Type.DOUBLE;
case BOTTOM -> org.bukkit.block.data.type.Slab.Type.BOTTOM;
};
}
public static Location adapt(com.dfsek.terra.api.math.vector.Location location) {
@@ -5,8 +5,10 @@ import com.dfsek.terra.api.math.vector.Location;
import com.dfsek.terra.api.platform.handle.WorldHandle;
import com.dfsek.terra.api.platform.world.Tree;
import com.dfsek.terra.api.util.collections.MaterialSet;
import com.dfsek.terra.profiler.ProfileFrame;
import org.bukkit.TreeType;
import java.util.Locale;
import java.util.Random;
public class BukkitTree implements Tree {
@@ -22,26 +24,23 @@ public class BukkitTree implements Tree {
private MaterialSet getSpawnable(TreeType type) {
WorldHandle handle = main.getWorldHandle();
switch(type) {
case CRIMSON_FUNGUS:
return MaterialSet.get(handle.createBlockData("minecraft:crimson_nylium"));
case WARPED_FUNGUS:
return MaterialSet.get(handle.createBlockData("minecraft:warped_nylium"));
case BROWN_MUSHROOM:
case RED_MUSHROOM:
return MaterialSet.get(handle.createBlockData("minecraft:mycelium"), handle.createBlockData("minecraft:grass_block"),
handle.createBlockData("minecraft:podzol"));
case CHORUS_PLANT:
return MaterialSet.get(handle.createBlockData("minecraft:end_stone"));
default:
return MaterialSet.get(handle.createBlockData("minecraft:grass_block"), handle.createBlockData("minecraft:dirt"),
handle.createBlockData("minecraft:podzol"));
}
return switch(type) {
case CRIMSON_FUNGUS -> MaterialSet.get(handle.createBlockData("minecraft:crimson_nylium"));
case WARPED_FUNGUS -> MaterialSet.get(handle.createBlockData("minecraft:warped_nylium"));
case BROWN_MUSHROOM, RED_MUSHROOM -> MaterialSet.get(handle.createBlockData("minecraft:mycelium"), handle.createBlockData("minecraft:grass_block"),
handle.createBlockData("minecraft:podzol"));
case CHORUS_PLANT -> MaterialSet.get(handle.createBlockData("minecraft:end_stone"));
default -> MaterialSet.get(handle.createBlockData("minecraft:grass_block"), handle.createBlockData("minecraft:dirt"),
handle.createBlockData("minecraft:podzol"));
};
}
@Override
@SuppressWarnings("try")
public boolean plant(Location l, Random r) {
return ((BukkitWorld) l.getWorld()).getHandle().generateTree(BukkitAdapter.adapt(l), delegate);
try(ProfileFrame ignore = main.getProfiler().profile("bukkit_tree:" + delegate.toString().toLowerCase(Locale.ROOT))) {
return ((BukkitWorld) l.getWorld()).getHandle().generateTree(BukkitAdapter.adapt(l), delegate);
}
}
@Override
@@ -37,17 +37,14 @@ public class BukkitWorld implements World {
return new BukkitChunkGenerator(delegate.getGenerator());
}
@Override
public String getName() {
return delegate.getName();
}
@Override
public UUID getUID() {
return delegate.getUID();
}
@Override
public boolean isChunkGenerated(int x, int z) {
return delegate.isChunkGenerated(x, z);
}
@@ -57,7 +54,6 @@ public class BukkitWorld implements World {
return BukkitAdapter.adapt(delegate.getChunkAt(x, z));
}
@Override
public File getWorldFolder() {
return delegate.getWorldFolder();
}
@@ -20,29 +20,19 @@ public class BukkitWall extends BukkitWaterlogged implements Wall {
}
public static org.bukkit.block.data.type.Wall.Height adapt(com.dfsek.terra.api.platform.block.data.Wall.Height height) {
switch(height) {
case NONE:
return org.bukkit.block.data.type.Wall.Height.NONE;
case LOW:
return org.bukkit.block.data.type.Wall.Height.LOW;
case TALL:
return org.bukkit.block.data.type.Wall.Height.TALL;
default:
throw new IllegalStateException();
}
return switch(height) {
case NONE -> org.bukkit.block.data.type.Wall.Height.NONE;
case LOW -> org.bukkit.block.data.type.Wall.Height.LOW;
case TALL -> org.bukkit.block.data.type.Wall.Height.TALL;
};
}
public static com.dfsek.terra.api.platform.block.data.Wall.Height adapt(org.bukkit.block.data.type.Wall.Height height) {
switch(height) {
case TALL:
return com.dfsek.terra.api.platform.block.data.Wall.Height.TALL;
case LOW:
return com.dfsek.terra.api.platform.block.data.Wall.Height.LOW;
case NONE:
return com.dfsek.terra.api.platform.block.data.Wall.Height.NONE;
default:
throw new IllegalStateException();
}
return switch(height) {
case TALL -> Height.TALL;
case LOW -> Height.LOW;
case NONE -> Height.NONE;
};
}
@Override
@@ -96,32 +96,15 @@ public class BukkitMobSpawner extends BukkitBlockState implements MobSpawner {
public void applyState(String state) {
SerialState.parse(state).forEach((k, v) -> {
switch(k) {
case "type":
setSpawnedType(new BukkitEntityType(org.bukkit.entity.EntityType.valueOf(v.toUpperCase())));
return;
case "delay":
setDelay(Integer.parseInt(v));
return;
case "min_delay":
setMinSpawnDelay(Integer.parseInt(v));
return;
case "max_delay":
setMaxSpawnDelay(Integer.parseInt(v));
return;
case "spawn_count":
setSpawnCount(Integer.parseInt(v));
return;
case "spawn_range":
setSpawnRange(Integer.parseInt(v));
return;
case "max_nearby":
setMaxNearbyEntities(Integer.parseInt(v));
return;
case "required_player_range":
setRequiredPlayerRange(Integer.parseInt(v));
return;
default:
throw new IllegalArgumentException("Invalid property: " + k);
case "type" -> setSpawnedType(new BukkitEntityType(org.bukkit.entity.EntityType.valueOf(v.toUpperCase())));
case "delay" -> setDelay(Integer.parseInt(v));
case "min_delay" -> setMinSpawnDelay(Integer.parseInt(v));
case "max_delay" -> setMaxSpawnDelay(Integer.parseInt(v));
case "spawn_count" -> setSpawnCount(Integer.parseInt(v));
case "spawn_range" -> setSpawnRange(Integer.parseInt(v));
case "max_nearby" -> setMaxNearbyEntities(Integer.parseInt(v));
case "required_player_range" -> setRequiredPlayerRange(Integer.parseInt(v));
default -> throw new IllegalArgumentException("Invalid property: " + k);
}
});
}

Some files were not shown because too many files have changed in this diff Show More