diff --git a/README.md b/README.md index 35322cf98..864038fa2 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # Iris default module This project owns the built-in Iris feature and setting sources under -`src/main/java/art/arcane/iris/engine`. The files retain their existing packages, pack fields and -direct dependencies on Iris internals. +`src/main/java/art/arcane/iris`. The files keep the packages and pack fields they had in Iris. They build against +the Iris API alone (see "Building" below); Iris depends on this project, never the reverse. Ported features are IrisApi modules that every pack loads before its own: object placement (`iris:prepare`, `iris:anchor`, `iris:validate`, `iris:bore`, `iris:blocks`, `iris:stilt`, @@ -145,34 +145,38 @@ Every built-in stage is a full port: the module owns its logic and per-engine st work out their reach from the pack when it loads. A dimension's `disabledComponents` turns a mantle stage off by its flag (`CARVED`, `OBJECT`, `FLOATING_OBJECT`, `JIGSAW`) or by its stage id. -Iris core and these sources still depend on each other. The Iris host build therefore compiles them -together as one source set. This keeps the existing class names and platform artifacts while the -features remain in a single physical source tree. It does not create an independent plugin artifact. +## Building -`source-patterns.txt` records the module's source ownership. The host's -`:core:verifyDefaultModuleOwnership` task rejects declared feature sources in core, undeclared Java -files here, and missing source families. `:core:bukkitPurityRatchet` checks this tree alongside -core against the existing allowlist. +This is a Gradle build of its own (`art.arcane:iris-module`). Its compile classpath is the Iris API +(`com.volmit:iris-api`, from the sibling `../IrisApi` checkout; never `iris-host`), VolmLib, Gson, Lombok and the JDK, +all `compileOnly`: a host provides them at runtime. VolmLib comes from a sibling `VolmLib` checkout when there is one, +found the way Iris finds it (`-PuseLocalVolmLib=false`, `-PlocalVolmLibDirectory=` or `VOLMLIB_DIR`), otherwise +from the published `volmLibCoordinate` in `gradle.properties`, which matches Iris's. Classes compile with Iris's options +(`-parameters`, no debug info) and `lombok.config` repeats Iris's, so they are the classes Iris shipped when it +compiled these sources itself. -From this directory, run `./gradlew check` to invoke the Iris host's joint compilation and purity -check and build the module sources archive. Run `./gradlew builtinSourcesJar` to build just the -archive. The host project also provides `:core:defaultModuleSourcesJar` for the same source tree. +Iris includes this build (`includeBuild('../IrisModule')` in its `settings.gradle`) and depends on its classes: Iris +core and its adapters still name many of them (the cut-over that ends this comes later). Classes that need Iris itself +are Iris's and live in Iris core: the layout model (`IrisBiome`, `IrisRegion`, `IrisDimension`, generators, noise +styles, expressions, images), the pack's objects and blocks, the structure model with its assembler, locator, fitting +and placer (behind `StructureHost`), and the object placers behind `ObjectHost` and `FloatingHost`. + +`./gradlew check` compiles every source and builds the built-ins jar below, which runs the pack class checks. ## Built-in modules as a pack module jar -Iris builds the built-in modules as an ordinary pack module jar, `iris-builtins.jar`, and bundles it into the plugin: -Iris's `:core:builtinModulesJar` packages it from core's compiled classes, so it always fits the Iris it ships with, and -every pack loads it as if it were in its `modules/` folder (IrisApi's `ModuleHost.bundlingJars`). A pack must not hold a -copy of it: its classes would be in two jars, so the pack fails to load naming both. `./gradlew builtinModulesJar` -here runs that task and copies the jar to `build/libs/iris-builtins.jar`. `builtin-modules.txt` lists what goes in: -`module ` lines (the jar's entry points, written to `META-INF/services/com.volmit.IrisModule`) and `include ` -lines for further classes. The plugin's own classes leave those classes out; Iris's Bukkit artifact check fails the build if -core still uses one of them. -Before the jar is used, `ModuleJarCheck` of IrisApi runs the class checks of a pack load on it, with the packages Iris +This build packages the built-in modules as an ordinary pack module jar, `build/libs/iris-builtins.jar`, from its own +classes, and Iris bundles it into the plugin: every pack loads it as if it were in its `modules/` folder (IrisApi's +`ModuleHost.bundlingJars`). A pack must not hold a copy of it: its classes would be in two jars, so the pack fails to load +naming both. `./gradlew builtinModulesJar` builds it. `builtin-modules.txt` lists what goes in: `module ` lines +(the jar's entry points, written to `META-INF/services/com.volmit.IrisModule`) and `include ` lines for further +classes. Iris asks for the jar by the capability `art.arcane:iris-builtins`; its plugin leaves the jar's classes out of +its own, and its Bukkit artifact check fails the build if Iris still uses one of them. +Before the jar is written, `ModuleJarCheck` of IrisApi runs the class checks of a pack load on it, with the packages Iris exposes (`art.arcane.iris.builtin`, VolmLib's `art.arcane.volmlib` and Gson's `com.google.gson`, all three on the check's -classpath); a listed class that uses Iris internals fails the task naming the class and what it uses. A VolmLib class that -Iris's Bukkit jar strips (the list is Iris's `core/volmlib-left-out-of-bukkit-jar.txt`, which its shadowJar reads too) is on -that classpath but missing on a server, so the check treats it as missing and fails the task naming it. `check` runs the task. +classpath, with this build's other classes as the host's); a listed class that uses a class outside the jar and those +packages fails the task naming the class and what it uses. Iris checks the jar once more before bundling it, against the +VolmLib classes its Bukkit jar strips (`core/volmlib-left-out-of-bukkit-jar.txt`), which only Iris knows. The jar holds `iris:post`, `iris:perfection`, `iris:matter`, `iris:loot`, `iris:spawn`, `iris:vanilla-features` and `iris:carve`, and the object placement stages `iris:prepare`, `iris:anchor`, `iris:validate`, `iris:bore`, `iris:blocks`, `iris:stilt`, `iris:vacuum` and `iris:snow`. They are diff --git a/build.gradle.kts b/build.gradle.kts index 634021283..a9122a20e 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,62 +1,179 @@ import org.gradle.jvm.tasks.Jar +import java.io.ByteArrayOutputStream plugins { - base - `java-base` + `java-library` } group = "art.arcane" version = "1.0-SNAPSHOT" -val irisRoot = rootDir.resolve("../Iris").canonicalFile -val moduleSources = layout.projectDirectory.dir("src/main/java") - -tasks.register("builtinSourcesJar") { - group = "build" - description = "Packages the built-in Iris sources owned by this module." - archiveBaseName.set("iris-default-module") - archiveClassifier.set("sources") - destinationDirectory.set(layout.buildDirectory.dir("libs")) - inputs.dir(moduleSources) - from(moduleSources) +base { + archivesName.set("iris-module") } -val checkBuiltins = tasks.register("checkBuiltins") { - group = "verification" - description = "Compiles the built-ins with Iris and checks source ownership and Bukkit purity." - workingDir(irisRoot) - commandLine( - "./gradlew", - ":core:compileJava", - ":core:bukkitPurityRatchet", - "-PincludeModdedAdapters=false", - "--console=plain", - ) +java { + toolchain.languageVersion.set(JavaLanguageVersion.of(25)) + withSourcesJar() } -// The built-ins as a pack module jar. Iris packages and checks it from its own compiled classes (core's builtinModulesJar, -// which reads builtin-modules.txt) and bundles it into the plugin; this copies it to build/libs for other hosts and tools. +repositories { + mavenCentral() + maven("https://jitpack.io") // VolmLib, when no sibling checkout is found +} + +val volmLibCoordinate = providers.gradleProperty("volmLibCoordinate").get() + +// What a module may use: the Iris API, VolmLib and Gson, which every Iris host provides, and the JDK. None of them ships +// with the module. +dependencies { + compileOnly("com.volmit:iris-api") + compileOnly(volmLibCoordinate) { + isTransitive = false + } + compileOnly("com.google.code.gson:gson:2.14.0") + compileOnly("org.projectlombok:lombok:1.18.46") + annotationProcessor("org.projectlombok:lombok:1.18.46") +} + +// The same options as Iris's own compilation, so the classes, and the built-ins jar made from them, are the ones Iris +// shipped when it compiled these sources itself. +tasks.named("compileJava") { + options.encoding = "UTF-8" + options.compilerArgs.add("-parameters") + options.debugOptions.debugLevel = "none" + // lombok.config decides which members Lombok generates; Gradle does not know it is an input. + inputs.file(layout.projectDirectory.file("lombok.config")) + .withPropertyName("lombokConfig") + .withPathSensitivity(PathSensitivity.NONE) +} + +// The built-ins as a pack module jar, build/libs/iris-builtins.jar. builtin-modules.txt lists what goes in: +// "module " (an entry point, with its nested classes) or "include ". val builtinModulesJarName = "iris-builtins.jar" +val builtinModuleEntryFile = "com.volmit.IrisModule" +val builtinModulesFile = layout.projectDirectory.file("builtin-modules.txt").asFile +// The packages an Iris host exposes to pack modules besides the API (Iris's IrisModuleHost.EXPOSED_PACKAGES). +val exposedHostPackages = listOf("art.arcane.iris.builtin", "art.arcane.volmlib", "com.google.gson") -val packageBuiltinModulesInIris = tasks.register("packageBuiltinModulesInIris") { - description = "Runs Iris's :core:builtinModulesJar, which compiles Iris with the built-ins, packages and checks the jar." - workingDir(irisRoot) - val offline = if (gradle.startParameter.isOffline) listOf("--offline") else emptyList() - commandLine(listOf("./gradlew", ":core:builtinModulesJar", "-PincludeModdedAdapters=false", "--console=plain") + offline) +data class BuiltinModulesList(val moduleClasses: List, val classPatterns: List) + +fun readBuiltinModulesList(): BuiltinModulesList { + val moduleClasses = mutableListOf() + val classPatterns = mutableListOf() + builtinModulesFile.readLines() + .map { it.substringBefore('#').trim() } + .filter { it.isNotEmpty() } + .forEach { line -> + val parts = line.split(Regex("\\s+"), limit = 2) + if (parts.size < 2 || parts[1].isBlank()) { + throw GradleException("${builtinModulesFile.name}: '$line' needs a value after '${parts[0]}'") + } + when (parts[0]) { + "module" -> moduleClasses.add(parts[1].trim()) + "include" -> classPatterns.add(parts[1].trim()) + else -> throw GradleException("${builtinModulesFile.name}: unknown line '$line'; start it with 'module' or 'include'") + } + } + return BuiltinModulesList(moduleClasses, classPatterns) } -tasks.register("builtinModulesJar") { +val builtinModulesList = readBuiltinModulesList() +val builtinPackagedPatterns = builtinModulesList.moduleClasses.flatMap { moduleClass -> + val path = moduleClass.replace('.', '/') + listOf("$path.class", "$path\$*.class") +} + builtinModulesList.classPatterns +val builtinModulesBuild = layout.buildDirectory.dir("builtin-modules") + +val writeBuiltinModuleEntries = tasks.register("writeBuiltinModuleEntries") { + description = "Writes the built-ins jar's META-INF/services/$builtinModuleEntryFile, one module class per line." + val entries = builtinModulesBuild.map { it.file("services/$builtinModuleEntryFile") } + inputs.file(builtinModulesFile) + outputs.file(entries) + doLast { + val entriesFile = entries.get().asFile + entriesFile.parentFile.mkdirs() + entriesFile.writeText(builtinModulesList.moduleClasses.joinToString("\n") + "\n") + } +} + +val packageBuiltinModules = tasks.register("packageBuiltinModules") { + description = "Packages the listed built-in modules and classes before they are checked." + archiveFileName.set(builtinModulesJarName) + destinationDirectory.set(builtinModulesBuild.map { it.dir("unchecked") }) + inputs.file(builtinModulesFile) + from(sourceSets.main.map { it.java.classesDirectory }) { + include(builtinPackagedPatterns) + } + from(writeBuiltinModuleEntries) { + into("META-INF/services") + } +} + +// The check runs on the API's host side, which knows the rules of a pack load; the module classes are on its class path as +// the host's, so a listed class that uses one left out of the jar fails as it would in Iris. +val builtinModulesCheckClasspath = configurations.create("builtinModulesCheckClasspath") { + isCanBeConsumed = false + isTransitive = false + attributes { + attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME)) + } +} + +dependencies { + builtinModulesCheckClasspath("com.volmit:iris-api") + builtinModulesCheckClasspath("com.volmit:iris-host") + builtinModulesCheckClasspath(volmLibCoordinate) + builtinModulesCheckClasspath("com.google.code.gson:gson:2.14.0") +} + +val builtinModulesJar = tasks.register("builtinModulesJar") { group = "build" - description = "Copies the checked jar Iris built to build/libs/$builtinModulesJarName, the built-in modules as a pack module jar." - dependsOn(packageBuiltinModulesInIris) - from(irisRoot.resolve("core/build/builtin-modules/$builtinModulesJarName")) - into(layout.buildDirectory.dir("libs")) + description = "Builds build/libs/$builtinModulesJarName, the built-in modules as a pack module jar, checked with IrisApi's" + + " pack class and reference checks as a pack load would." + val unchecked = packageBuiltinModules.flatMap { it.archiveFile } + val checked = layout.buildDirectory.file("libs/$builtinModulesJarName") + classpath = builtinModulesCheckClasspath + files(sourceSets.main.map { it.java.classesDirectory }) + mainClass.set("com.volmit.host.ModuleJarCheck") + inputs.file(unchecked) + outputs.file(checked) + argumentProviders.add(CommandLineArgumentProvider { listOf(unchecked.get().asFile.absolutePath) + exposedHostPackages }) + isIgnoreExitValue = true + val problems = ByteArrayOutputStream() + errorOutput = problems + doFirst { + // A jar from an earlier run that passed must not survive a run that fails. + checked.get().asFile.delete() + } + doLast { + if (executionResult.get().exitValue != 0) { + throw GradleException("The built-in modules jar breaks the rules of a pack module jar:\n" + problems.toString().trim() + + "\nFix the classes listed in ${builtinModulesFile.name}, or move what they use into the jar or into art.arcane.iris.builtin.") + } + unchecked.get().asFile.copyTo(checked.get().asFile, overwrite = true) + } +} + +// Iris bundles the checked jar into its plugin. It asks for it by this capability of the module's coordinate. +configurations.create("builtinModulesJarElements") { + isCanBeConsumed = true + isCanBeResolved = false + attributes { + attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME)) + attribute(Category.CATEGORY_ATTRIBUTE, objects.named(Category.LIBRARY)) + attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, objects.named(LibraryElements.JAR)) + attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling.EXTERNAL)) + } + outgoing.capability("art.arcane:iris-builtins:${project.version}") + outgoing.artifact(builtinModulesJar.map { layout.buildDirectory.file("libs/$builtinModulesJarName").get() }) { + builtBy(builtinModulesJar) + } } tasks.named("check") { - dependsOn(checkBuiltins, "builtinSourcesJar", "builtinModulesJar") + dependsOn(builtinModulesJar) } tasks.named("assemble") { - dependsOn("builtinSourcesJar") + dependsOn(builtinModulesJar) } diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 000000000..966645f9f --- /dev/null +++ b/gradle.properties @@ -0,0 +1,3 @@ +# The published VolmLib the build resolves when no sibling checkout is found (see settings.gradle.kts). Keep it equal to +# Iris's volmLibCoordinate: Iris ships VolmLib and the built-ins run against that copy. +volmLibCoordinate=com.github.VolmitSoftware:VolmLib:e6574cf814b3dd670385a4d632a63fde2038e186 diff --git a/lombok.config b/lombok.config index 5e8c64b0e..803015b8e 100644 --- a/lombok.config +++ b/lombok.config @@ -1,6 +1,5 @@ -# These sources compile together with Iris core and must generate the same members, so this repeats -# ../Iris/lombok.config, which Lombok never reaches from here: it looks upward from each source file. -# Keep the two in sync; ../Iris/lombok.config explains each setting. +# Iris compiled these sources itself before they had a build of their own, so this repeats ../Iris/lombok.config to keep +# the members Lombok generates, and with them the classes Iris ships, unchanged. ../Iris/lombok.config explains each setting. config.stopBubbling = true lombok.equalsAndHashCode.doNotUseGetters = true lombok.toString.doNotUseGetters = true diff --git a/settings.gradle.kts b/settings.gradle.kts index a480323b7..500d94cba 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,4 +1,42 @@ rootProject.name = "IrisModule" -// Keep the public API discoverable when importing the default module. -includeBuild("../IrisApi") +// The built-ins compile against the Iris API alone, from the sibling checkout. Never against iris-host: that is what a host +// such as Iris uses to load modules, and packs never see it. +includeBuild("../IrisApi") { + dependencySubstitution { + substitute(module("com.volmit:iris-api")).using(project(":api")) + substitute(module("com.volmit:iris-host")).using(project(":host")) + } +} + +// VolmLib from a sibling checkout when there is one, as Iris resolves it (Iris's gradle/volmlib-resolution.settings.gradle): +// -PuseLocalVolmLib=false turns it off, -PlocalVolmLibDirectory= or VOLMLIB_DIR names the checkout, and otherwise the +// first `VolmLib` folder with a settings script above this one is used. Without one, the build resolves the published +// coordinate in gradle.properties. +fun hasSettingsScript(directory: File): Boolean = + File(directory, "settings.gradle.kts").exists() || File(directory, "settings.gradle").exists() + +fun localVolmLibDirectory(): File? { + val configuredPath = providers.gradleProperty("localVolmLibDirectory") + .orElse(providers.environmentVariable("VOLMLIB_DIR")) + .orNull + if (!configuredPath.isNullOrBlank()) { + val configured = File(configuredPath).let { if (it.isAbsolute) it else File(settingsDir, configuredPath) } + if (hasSettingsScript(configured)) { + return configured + } + } + return generateSequence(settingsDir) { it.parentFile } + .map { File(it, "VolmLib") } + .firstOrNull { hasSettingsScript(it) } +} + +val useLocalVolmLib = providers.gradleProperty("useLocalVolmLib").orElse("true").get().equals("true", ignoreCase = true) +val volmLibCheckout = if (useLocalVolmLib) localVolmLibDirectory() else null +if (volmLibCheckout != null) { + includeBuild(volmLibCheckout) { + dependencySubstitution { + substitute(module("com.github.VolmitSoftware:VolmLib")).using(project(":shared")) + } + } +} diff --git a/source-patterns.txt b/source-patterns.txt deleted file mode 100644 index bd9d2ba02..000000000 --- a/source-patterns.txt +++ /dev/null @@ -1,19 +0,0 @@ -art/arcane/iris/engine/actuator/** -art/arcane/iris/engine/decorator/** -art/arcane/iris/engine/modifier/** -art/arcane/iris/engine/mantle/components/** -art/arcane/iris/engine/object/** -art/arcane/iris/engine/image/** -art/arcane/iris/engine/framework/structure/** -art/arcane/iris/engine/framework/vanillafeatures/** -art/arcane/iris/engine/framework/StructureAssembler.java -art/arcane/iris/engine/framework/IrisStructureLocator.java -art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java -art/arcane/iris/engine/framework/StructurePlacementScope.java -art/arcane/iris/engine/framework/StructurePlacementGrid.java -art/arcane/iris/engine/framework/StructureVerticalBounds.java -art/arcane/iris/engine/framework/PlacedObject.java -art/arcane/iris/engine/framework/PlacedStructurePiece.java -art/arcane/iris/builtin/** -art/arcane/iris/engine/loot/** -art/arcane/iris/engine/spawn/** diff --git a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java deleted file mode 100644 index f9b7df408..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java +++ /dev/null @@ -1,1322 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.framework; - -import art.arcane.iris.builtin.anchor.PlaceTrait; -import art.arcane.iris.engine.framework.structure.NativeStartPlanner; -import art.arcane.iris.engine.framework.structure.StructureResources; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.structure.StructureGraphCatalog; -import art.arcane.iris.engine.framework.structure.StructureGraphCompilation; -import art.arcane.iris.engine.framework.structure.StructureAssemblyResult; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.builtin.structure.NativeStructureSource; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.iris.builtin.structure.StructureAnchorMode; -import art.arcane.iris.builtin.structure.StructureCarveShape; -import art.arcane.iris.builtin.structure.StructurePlacement; -import art.arcane.iris.builtin.structure.StructureTerrain; -import art.arcane.iris.builtin.structure.StructureTerrainMode; -import art.arcane.iris.builtin.structure.NativeStructureSuppression; -import art.arcane.iris.builtin.structure.StructureDistribution; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.core.modules.IrisModuleHost; -import com.volmit.ModuleLog; -import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Locale; -import java.util.Objects; -import java.util.Set; -import java.util.regex.Pattern; - -/** - * Finds where Iris assembly and native jigsaw placements generate. A structure key matches - * an Iris structure load key, its {@code vanillaSource}, or a configured native registry key. - * - * Each world keeps an index of placed keys in its state, so {@code /locate} and {@code /iris goto} skip - * the grid scan entirely for keys that are not placed (keeping them as fast as vanilla). - * - * For RANDOM_SPREAD placements (the common, vanilla-style spaced grid) the locator jumps - * straight to the single candidate chunk in each spacing-sized grid cell rather than testing - * every chunk -- roughly a {@code spacing^2} reduction in placement checks, matching vanilla - * locate performance. Density placements use a bounded per-chunk ring scan, while concentric - * placements enumerate their finite configured starts directly. - */ -public final class IrisStructureLocator { - private static final int CANDIDATE_BUDGET = 4_096; - private static final int MAX_BURIAL_COLUMNS = 2_000_000; - private static final int UNDERGROUND_SURFACE_CLEARANCE = 1; - private static final long CAVE_ANCHOR_DOMAIN = 0x43415645414E4348L; - private static final Pattern NAMESPACED_RESOURCE_KEY = Pattern.compile("[a-z0-9_.-]+:[a-z0-9/._-]+"); - - private static final PlacementIndex EMPTY_INDEX = new PlacementIndex( - Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), - Collections.emptySet(), Collections.emptyList()); - private static final LocatableIndex EMPTY_LOCATABLE_INDEX = new LocatableIndex( - Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), - Collections.emptySet(), Collections.emptySet(), Collections.emptySet()); - private static final LocateResult NOT_FOUND_RESULT = new LocateResult(LocateStatus.NOT_FOUND, 0, 0, 0); - private static final LocateResult SEARCH_LIMIT_RESULT = - new LocateResult(LocateStatus.SEARCH_LIMIT_REACHED, 0, 0, 0); - - private IrisStructureLocator() { - } - - /** Structure keys referenced by any Iris assembly or native jigsaw placement. */ - public static Set placedKeys(Engine engine) { - if (engine == null) { - return Collections.emptySet(); - } - return index(engine).loadKeys; - } - - /** - * Every key under which a structure the engine's placements place can be found: the placed keys and the platform - * structures Iris structures stand in for ({@code vanillaSource}), the latter in lower case. - */ - public static Set placedKeysAndAliases(Engine engine) { - if (engine == null) { - return Collections.emptySet(); - } - PlacementIndex placementIndex = index(engine); - Set keys = new LinkedHashSet<>(placementIndex.loadKeys); - keys.addAll(placementIndex.vanillaAliases); - return Collections.unmodifiableSet(keys); - } - - /** The platform structures the engine's placements start natively ({@code nativeStructures}), in lower case. */ - public static Set nativeKeys(Engine engine) { - if (engine == null) { - return Collections.emptySet(); - } - return index(engine).nativeKeys; - } - - public static boolean isPlaced(Engine engine, String key) { - if (engine == null || key == null || key.isEmpty()) { - return false; - } - PlacementIndex placementIndex = index(engine); - String normalizedKey = normalize(key); - return placementIndex.normalizedLoadKeys.contains(normalizedKey) - || placementIndex.vanillaAliases.contains(normalizedKey); - } - - public static boolean hasLocatablePlacement(Engine engine, String key) { - if (engine == null || key == null || key.isBlank()) { - return false; - } - return locatableIndex(engine).normalizedKeys().contains(normalize(key)); - } - - public static boolean hasLocatableEditablePlacement(Engine engine, String key) { - if (engine == null || key == null || key.isBlank()) { - return false; - } - return locatableIndex(engine).normalizedEditableKeys().contains(normalize(key)); - } - - public static boolean hasLocatableNativePlacement(Engine engine, String key) { - if (engine == null || key == null || key.isBlank()) { - return false; - } - return locatableIndex(engine).normalizedNativeKeys().contains(normalize(key)); - } - - public static Set locatableKeys(Engine engine) { - return locatableIndex(engine).keys(); - } - - public static Set locatableEditableKeys(Engine engine) { - return locatableIndex(engine).editableKeys(); - } - - public static Set locatableNativeKeys(Engine engine) { - return locatableIndex(engine).nativeKeys(); - } - - public static boolean hasNativePlacement(Engine engine, String key) { - if (engine == null || key == null || key.isBlank()) { - return false; - } - return index(engine).nativeKeys.contains(normalize(key)); - } - - public static boolean hasEditablePlacement(Engine engine, String key) { - if (engine == null || key == null || key.isBlank()) { - return false; - } - for (StructurePlacement placement : index(engine).placements) { - if (placement.hasIrisStructures() && matches(placement, key, engine.getData())) { - return true; - } - } - return false; - } - - public static boolean suppressesVanilla(Engine engine, String vanillaKey) { - if (engine == null || vanillaKey == null || vanillaKey.isEmpty()) { - return false; - } - return index(engine).suppressedVanillaSources.contains(normalize(vanillaKey)); - } - - public static boolean startsInChunk(Engine engine, String key, int cx, int cz) { - if (!isPlaced(engine, key)) { - return false; - } - return resolveInChunk(engine, key, cx, cz) != null; - } - - public static LocateResult locate(Engine engine, String key, int fromBlockX, int fromBlockZ, int maxRadiusChunks) { - return locate(engine, key, fromBlockX, fromBlockZ, maxRadiusChunks, (chunkX, chunkZ) -> true); - } - - public static LocateResult locate(Engine engine, String key, int fromBlockX, int fromBlockZ, - int maxRadiusChunks, CandidateFilter candidateFilter) { - try { - return locateFiltered(engine, key, fromBlockX, fromBlockZ, maxRadiusChunks, candidateFilter); - } catch (CandidateSearchLimitException ignored) { - return SEARCH_LIMIT_RESULT; - } - } - - public static LocateResult locateInPlacementRings( - Engine engine, String key, int fromBlockX, int fromBlockZ, - int maxSearchRadius, CandidateFilter candidateFilter) { - try { - return locateInPlacementRingsFiltered( - engine, key, fromBlockX, fromBlockZ, maxSearchRadius, candidateFilter); - } catch (CandidateSearchLimitException ignored) { - return SEARCH_LIMIT_RESULT; - } - } - - private static LocateResult locateInPlacementRingsFiltered( - Engine engine, String key, int fromBlockX, int fromBlockZ, - int maxSearchRadius, CandidateFilter candidateFilter) { - if (!isPlaced(engine, key)) { - return NOT_FOUND_RESULT; - } - CandidateFilter activeFilter = Objects.requireNonNull( - candidateFilter, "Structure locate filter must not be null"); - int maximumRing = Math.max(0, Math.min(maxSearchRadius, 2048)); - int centerChunkX = fromBlockX >> 4; - int centerChunkZ = fromBlockZ >> 4; - PlacementCatalog catalog = collectPlacementCatalog(engine, key); - if (catalog.randomSpread().isEmpty() - && catalog.concentricRings().isEmpty() && !catalog.hasDensity()) { - return NOT_FOUND_RESULT; - } - SeedManager seedManager = engine.getSeedManager(); - if (seedManager == null) { - throw new IllegalStateException( - "Iris structure locate requires a bound seed manager for '" + key + "'"); - } - long seed = seedManager.getMantle(); - CandidateBudget candidateBudget = new CandidateBudget(); - LocatedCandidate best = nearestConcentricCandidate( - engine, key, fromBlockX, fromBlockZ, seed, catalog, activeFilter, candidateBudget); - - for (int ring = 0; ring <= maximumRing; ring++) { - boolean foundInRing = false; - for (RandomSpreadParameters parameters : catalog.randomSpread()) { - LocatedCandidate candidate = firstRandomSpreadCandidateInRing( - engine, key, fromBlockX, fromBlockZ, - centerChunkX, centerChunkZ, ring, seed, - parameters, activeFilter, candidateBudget); - if (candidate == null) { - continue; - } - foundInRing = true; - if (best == null || candidate.distanceSquared() < best.distanceSquared()) { - best = candidate; - } - } - if (catalog.hasDensity()) { - LocatedCandidate candidate = firstDensityCandidateInRing( - engine, key, fromBlockX, fromBlockZ, - centerChunkX, centerChunkZ, ring, - activeFilter, candidateBudget); - if (candidate != null) { - foundInRing = true; - if (best == null || candidate.distanceSquared() < best.distanceSquared()) { - best = candidate; - } - } - } - if (foundInRing) { - return found(best); - } - } - return best == null ? NOT_FOUND_RESULT : found(best); - } - - private static LocatedCandidate nearestConcentricCandidate( - Engine engine, String key, int fromBlockX, int fromBlockZ, - long seed, PlacementCatalog catalog, CandidateFilter candidateFilter, - CandidateBudget candidateBudget) { - LocatedCandidate best = null; - Set checkedChunks = new LinkedHashSet<>(); - for (StructurePlacement placement : catalog.concentricRings()) { - int count = Math.max(1, placement.ringCount()); - for (int placementIndex = 0; placementIndex < count; placementIndex++) { - candidateBudget.claim(); - int[] candidate = StructurePlacementGrid.concentricRingChunk( - placement, placementIndex, seed); - if (candidate == null || !checkedChunks.add(chunkKey(candidate[0], candidate[1]))) { - continue; - } - ResolvedStart resolved = resolveInChunk(engine, key, candidate[0], candidate[1]); - if (resolved == null || !candidateFilter.accept(candidate[0], candidate[1])) { - continue; - } - long distanceSquared = blockDistanceSquared( - resolved, fromBlockX, fromBlockZ); - if (best == null || distanceSquared < best.distanceSquared()) { - best = new LocatedCandidate(resolved, distanceSquared); - } - } - } - return best; - } - - private static LocatedCandidate firstRandomSpreadCandidateInRing( - Engine engine, String key, int fromBlockX, int fromBlockZ, - int centerChunkX, int centerChunkZ, int ring, long seed, - RandomSpreadParameters parameters, CandidateFilter candidateFilter, - CandidateBudget candidateBudget) { - int spacing = Math.max(1, parameters.spacing()); - int centerCellX = Math.floorDiv(centerChunkX, spacing); - int centerCellZ = Math.floorDiv(centerChunkZ, spacing); - for (int offsetX = -ring; offsetX <= ring; offsetX++) { - boolean edgeX = offsetX == -ring || offsetX == ring; - for (int offsetZ = -ring; offsetZ <= ring; offsetZ++) { - boolean edgeZ = offsetZ == -ring || offsetZ == ring; - if (!edgeX && !edgeZ) { - continue; - } - candidateBudget.claim(); - int[] candidate = StructurePlacementGrid.randomSpreadCellChunk( - centerCellX + offsetX, centerCellZ + offsetZ, - spacing, parameters.separation(), parameters.salt(), seed); - ResolvedStart resolved = resolveInChunk(engine, key, candidate[0], candidate[1]); - if (resolved != null && candidateFilter.accept(candidate[0], candidate[1])) { - return new LocatedCandidate( - resolved, blockDistanceSquared(resolved, fromBlockX, fromBlockZ)); - } - } - } - return null; - } - - private static LocatedCandidate firstDensityCandidateInRing( - Engine engine, String key, int fromBlockX, int fromBlockZ, - int centerChunkX, int centerChunkZ, int ring, - CandidateFilter candidateFilter, CandidateBudget candidateBudget) { - for (int offsetX = -ring; offsetX <= ring; offsetX++) { - boolean edgeX = offsetX == -ring || offsetX == ring; - for (int offsetZ = -ring; offsetZ <= ring; offsetZ++) { - boolean edgeZ = offsetZ == -ring || offsetZ == ring; - if (!edgeX && !edgeZ) { - continue; - } - int chunkX = centerChunkX + offsetX; - int chunkZ = centerChunkZ + offsetZ; - candidateBudget.claim(); - ResolvedStart resolved = resolveInChunk(engine, key, chunkX, chunkZ); - if (resolved != null && candidateFilter.accept(chunkX, chunkZ)) { - return new LocatedCandidate( - resolved, blockDistanceSquared(resolved, fromBlockX, fromBlockZ)); - } - } - } - return null; - } - - private static LocateResult locateFiltered(Engine engine, String key, int fromBlockX, int fromBlockZ, - int maxRadiusChunks, CandidateFilter candidateFilter) { - if (!isPlaced(engine, key)) { - return NOT_FOUND_RESULT; - } - CandidateFilter activeFilter = Objects.requireNonNull(candidateFilter, "Structure locate filter must not be null"); - int max = Math.max(0, Math.min(maxRadiusChunks, 2048)); - int pcx = fromBlockX >> 4; - int pcz = fromBlockZ >> 4; - LocatedCandidate best = null; - PlacementCatalog catalog = collectPlacementCatalog(engine, key); - if (catalog.randomSpread().isEmpty() && catalog.concentricRings().isEmpty() && !catalog.hasDensity()) { - return NOT_FOUND_RESULT; - } - SeedManager seedManager = engine.getSeedManager(); - if (seedManager == null) { - throw new IllegalStateException("Iris structure locate requires a bound seed manager for '" + key + "'"); - } - long seed = seedManager.getMantle(); - CandidateBudget candidateBudget = new CandidateBudget(); - - for (RandomSpreadParameters parameters : catalog.randomSpread) { - int spacing = Math.max(1, parameters.spacing()); - int centerCellX = Math.floorDiv(pcx, spacing); - int centerCellZ = Math.floorDiv(pcz, spacing); - int cellRadius = (max / spacing) + 2; - - for (int r = 0; r <= cellRadius; r++) { - long chunkLowerBound = cellRingDistanceLowerBound( - r, spacing, pcx, pcz, centerCellX, centerCellZ); - long blockLowerBound = chunkDeltaBlockDistanceLowerBound(chunkLowerBound); - if (best != null && squareSaturated(blockLowerBound) >= best.distanceSquared()) { - break; - } - for (int dx = -r; dx <= r; dx++) { - for (int dz = -r; dz <= r; dz++) { - if (Math.max(Math.abs(dx), Math.abs(dz)) != r) { - continue; - } - candidateBudget.claim(); - int[] candidate = StructurePlacementGrid.randomSpreadCellChunk( - centerCellX + dx, centerCellZ + dz, spacing, parameters.separation(), parameters.salt(), seed); - int cx = candidate[0]; - int cz = candidate[1]; - if (!withinRadius(cx, cz, pcx, pcz, max) - || best != null && chunkBlockDistanceSquaredLowerBound( - cx, cz, fromBlockX, fromBlockZ) >= best.distanceSquared()) { - continue; - } - ResolvedStart resolved = resolveInChunk(engine, key, cx, cz); - if (resolved != null && activeFilter.accept(cx, cz)) { - long distanceSquared = blockDistanceSquared( - resolved, fromBlockX, fromBlockZ); - if (best == null || distanceSquared < best.distanceSquared()) { - best = new LocatedCandidate(resolved, distanceSquared); - } - } - } - } - } - } - - Set checkedRingChunks = new LinkedHashSet<>(); - for (StructurePlacement placement : catalog.concentricRings) { - int count = Math.max(1, placement.ringCount()); - for (int placementIndex = 0; placementIndex < count; placementIndex++) { - candidateBudget.claim(); - int[] candidate = StructurePlacementGrid.concentricRingChunk(placement, placementIndex, seed); - if (candidate == null || !checkedRingChunks.add(chunkKey(candidate[0], candidate[1]))) { - continue; - } - if (!withinRadius(candidate[0], candidate[1], pcx, pcz, max) - || best != null && chunkBlockDistanceSquaredLowerBound( - candidate[0], candidate[1], fromBlockX, fromBlockZ) >= best.distanceSquared()) { - continue; - } - ResolvedStart resolved = resolveInChunk(engine, key, candidate[0], candidate[1]); - if (resolved != null && activeFilter.accept(candidate[0], candidate[1])) { - long distanceSquared = blockDistanceSquared( - resolved, fromBlockX, fromBlockZ); - if (best == null || distanceSquared < best.distanceSquared()) { - best = new LocatedCandidate(resolved, distanceSquared); - } - } - } - } - - if (catalog.hasDensity) { - for (int r = 0; r <= max; r++) { - long ringBlockLowerBound = chunkDeltaBlockDistanceLowerBound(r); - if (best != null && squareSaturated(ringBlockLowerBound) >= best.distanceSquared()) { - break; - } - for (int dx = -r; dx <= r; dx++) { - for (int dz = -r; dz <= r; dz++) { - if (Math.max(Math.abs(dx), Math.abs(dz)) != r) { - continue; - } - int cx = pcx + dx; - int cz = pcz + dz; - if (best != null && chunkBlockDistanceSquaredLowerBound( - cx, cz, fromBlockX, fromBlockZ) >= best.distanceSquared()) { - continue; - } - candidateBudget.claim(); - ResolvedStart resolved = resolveInChunk(engine, key, cx, cz); - if (resolved != null && activeFilter.accept(cx, cz)) { - long distanceSquared = blockDistanceSquared( - resolved, fromBlockX, fromBlockZ); - if (best == null || distanceSquared < best.distanceSquared()) { - best = new LocatedCandidate(resolved, distanceSquared); - } - } - } - } - } - } - - if (best == null) { - return NOT_FOUND_RESULT; - } - return found(best); - } - - static boolean withinRadius(int chunkX, int chunkZ, - int centerChunkX, int centerChunkZ, int radius) { - return Math.abs((long) chunkX - centerChunkX) <= radius - && Math.abs((long) chunkZ - centerChunkZ) <= radius; - } - - public static ResolvedPlacement resolvePlacement(Engine engine, StructurePlacement placement, int cx, int cz) { - if (engine == null || engine.getData() == null || engine.getSeedManager() == null) { - throw new IllegalStateException("Iris structure placement requires a fully bound engine"); - } - NativeStartPlanner.validateBackend(placement); - if (!placement.hasIrisStructures()) { - throw new IllegalStateException("Iris structure placement is missing its structure list"); - } - long seed = engine.getSeedManager().getMantle(); - if (!StructurePlacementGrid.startsInChunk(placement, cx, cz, seed)) { - return null; - } - - RNG rng = StructurePlacementGrid.placementRng(placement, cx, cz, seed); - int originX = (cx << 4) + rng.nextInt(16); - int originZ = (cz << 4) + rng.nextInt(16); - PlacementAnchor anchor = resolveAnchor(engine, placement, cx, cz, originX, originZ, rng); - if (anchor == null) { - return null; - } - originX = anchor.x(); - originZ = anchor.z(); - int baseY = anchor.y(); - - String selectedKey = selectStructureKey(placement, rng); - if (selectedKey == null || selectedKey.isBlank()) { - throw new IllegalStateException("Iris structure placement selected a blank structure key"); - } - IrisStructure structure = StructureResources.structure(engine.getData(), selectedKey); - if (structure == null) { - throw new IllegalStateException("Iris structure placement references missing structure '" - + selectedKey + "'"); - } - StructureGraphCompilation compilation = StructureGraphCatalog.compile(engine.getData(), structure, IrisModuleHost.hostLog()); - if (!compilation.isAssemblyViable()) { - throw new IllegalStateException("Iris structure '" + selectedKey - + "' has no runtime-viable assembly graph"); - } - - StructureAssembler assembler = StructureAssembler.forData( - engine.getData(), structure, new IrisPosition(originX, baseY, originZ), IrisModuleHost.hostLog()); - StructureAssemblyResult assembly = assembler.assemble(rng); - if (!requirePlacementOutput(placement, selectedKey, cx, cz, - assembly.hasOutput(), "runtime assembly produced " + assembly.status() + ": " + assembly.detail())) { - return null; - } - KList pieces = new KList<>(assembly.pieces()); - pieces = alignCavePieces(pieces, placement, baseY); - pieces = alignSurfacePieces(pieces, placement, structure, baseY); - if (!requirePlacementOutput(placement, selectedKey, cx, cz, - pieces != null && !pieces.isEmpty(), "surface alignment produced no pieces")) { - return null; - } - boolean exactY = hasExactY(placement, structure, pieces); - - int worldMin = engine.getMinHeight() + 1; - int worldMax = engine.getMinHeight() + engine.getHeight() - 1; - if (exactY) { - Integer verticalShift = resolveVerticalShift(pieces, placement, baseY, worldMin, worldMax); - if (!requirePlacementOutput(placement, selectedKey, cx, cz, verticalShift != null, - "assembled pieces cannot fit the configured vertical and world bounds")) { - return null; - } - if (verticalShift != 0) { - pieces = shiftPieces(pieces, verticalShift); - baseY += verticalShift; - } - } - if (placement.isAnchoredUnderground() && !placement.resolvedAnchor().isCave()) { - Integer burialShift = resolveUndergroundBurialShift( - engine, pieces, placement, baseY, worldMin, worldMax); - if (!requirePlacementOutput(placement, selectedKey, cx, cz, burialShift != null, - "assembled pieces and carving envelope cannot remain fully buried beneath terrain")) { - return null; - } - if (burialShift != 0) { - pieces = shiftPieces(pieces, burialShift); - baseY += burialShift; - } - } - - long configuredRadius = (long) Math.max(1, structure.getMaxSizeChunks()) * 16L; - int structureRadius = (int) Math.min(Integer.MAX_VALUE, configuredRadius); - boolean withinBounds = fitsHorizontalBounds(pieces, originX, originZ, structureRadius) - && (!exactY || fitsVerticalBounds(pieces, worldMin, worldMax)); - if (!requirePlacementOutput(placement, selectedKey, cx, cz, withinBounds, - "assembled pieces exceed the configured structure or world bounds")) { - return null; - } - return new ResolvedPlacement(placement, selectedKey, structure, pieces, rng, originX, baseY, originZ, exactY); - } - - public static boolean requirePlacementOutput(StructurePlacement placement, String structureKey, - int chunkX, int chunkZ, boolean outputPresent, - String failureReason) { - if (outputPresent) { - return true; - } - if (placement == null - || NativeStructureSuppression.REPLACE_SOURCE != placement.nativeSuppression()) { - return false; - } - String key = structureKey == null || structureKey.isBlank() - ? String.valueOf(placement.structures()) : structureKey; - String reason = failureReason == null || failureReason.isBlank() - ? "placement produced no output" : failureReason; - throw new IllegalStateException("REPLACE_SOURCE placement for Iris structure '" + key - + "' failed in chunk " + chunkX + "," + chunkZ + ": " + reason - + ". Native generation is suppressed and will not be used as a fallback"); - } - - static boolean fitsWorldBounds(KList pieces, int worldMin, int worldMax, - int originX, int originZ, int structureRadius) { - int[] bounds = computeBounds(pieces); - if (bounds == null) { - return false; - } - return fitsVerticalBounds(bounds, worldMin, worldMax) - && fitsHorizontalBounds(bounds, originX, originZ, structureRadius); - } - - private static ResolvedStart resolveInChunk(Engine engine, String key, int cx, int cz) { - IrisData data = engine.getData(); - String normalizedKey = normalize(key); - if (hasNativePlacement(engine, key)) { - for (NativeStartPlanner.Plan plan : NativeStartPlanner.plansAt(engine, cx, cz)) { - if (normalize(plan.source().structure()).equals(normalizedKey)) { - return new ResolvedStart(cx << 4, plan.baseY(), cz << 4); - } - } - } - KList placements = StructurePlacementScope.placementsAt(engine, cx, cz); - for (StructurePlacement placement : placements) { - if (!matches(placement, key, data)) { - continue; - } - if (placement.hasNativeStructures()) { - continue; - } - ResolvedPlacement resolved = resolvePlacement(engine, placement, cx, cz); - if (resolved != null && matchesResolved(resolved, key)) { - return new ResolvedStart( - resolved.originX(), resolved.baseY(), resolved.originZ()); - } - } - return null; - } - - private static PlacementAnchor resolveAnchor( - Engine engine, - StructurePlacement placement, - int chunkX, - int chunkZ, - int originX, - int originZ, - RNG rng - ) { - if (placement.resolvedAnchor().isCave()) { - StructureCaveAnchorResolver.Anchor caveAnchor = StructureCaveAnchorResolver.resolve( - engine, placement, chunkX, chunkZ, rng.nextParallelRNG(CAVE_ANCHOR_DOMAIN)); - return caveAnchor == null ? null : new PlacementAnchor(caveAnchor.x(), caveAnchor.y(), caveAnchor.z()); - } - Integer baseY = resolveBaseY(engine, placement, originX, originZ, rng); - return baseY == null ? null : new PlacementAnchor(originX, baseY, originZ); - } - - private static Integer resolveBaseY(Engine engine, StructurePlacement placement, int originX, int originZ, RNG rng) { - int worldMin = engine.getMinHeight() + 1; - int worldMax = engine.getMinHeight() + engine.getHeight() - 1; - if (worldMin > worldMax) { - return null; - } - if (!placement.underwater() - && NativeStartPlanner.isSubmerged(engine, originX, originZ)) { - return null; - } - if (placement.resolvedAnchor() == StructureAnchorMode.SURFACE) { - int surfaceY = engine.getHeight(originX, originZ, true) + engine.getMinHeight(); - return surfaceY < placement.minHeight() || surfaceY > placement.maxHeight() ? null : surfaceY; - } - int bandMin = Math.max(worldMin, Math.min(placement.minHeight(), placement.maxHeight())); - int bandMax = Math.min(worldMax, Math.max(placement.minHeight(), placement.maxHeight())); - if (bandMin > bandMax) { - return null; - } - return randomInclusive(rng, bandMin, bandMax); - } - - static Integer resolveVerticalShift(KList pieces, StructurePlacement placement, - int baseY, int worldMin, int worldMax) { - int[] bounds = computeBounds(pieces); - if (bounds == null) { - return null; - } - if (!placement.isAnchoredUnderground() || placement.resolvedAnchor().isCave()) { - return bounds[1] >= worldMin && bounds[4] <= worldMax ? 0 : null; - } - int bandMin = Math.max(worldMin, Math.min(placement.minHeight(), placement.maxHeight())); - int bandMax = Math.min(worldMax, Math.max(placement.minHeight(), placement.maxHeight())); - int minimumShift = Math.max(worldMin - bounds[1], bandMin - baseY); - int maximumShift = Math.min(worldMax - bounds[4], bandMax - baseY); - if (minimumShift > maximumShift) { - return null; - } - if (minimumShift > 0) { - return minimumShift; - } - if (maximumShift < 0) { - return maximumShift; - } - return 0; - } - - static Integer resolveUndergroundBurialShift(Engine engine, KList pieces, - StructurePlacement placement, int baseY, - int worldMin, int worldMax) { - int[] bounds = computeBounds(pieces); - if (engine == null || bounds == null || placement == null || !placement.isAnchoredUnderground() - || placement.resolvedAnchor().isCave()) { - return null; - } - - StructureTerrain terrain = placement.resolvedTerrain(); - StructureTerrainMode terrainMode = terrain.resolvedMode(); - boolean forceCarve = terrainMode == StructureTerrainMode.FORCE_CARVE; - boolean bore = terrainMode == StructureTerrainMode.BORE; - int sideExtension = forceCarve || bore ? Math.max(0, terrain.horizontalPadding()) : 0; - StructureCarveShape carveShape = terrain.resolvedShape(); - int topExtension = forceCarve - ? carveShape.maximumCeilingExtension( - terrain.ceilingPadding(), terrain.resolvedErosionStrength()) - : bore ? Math.max(0, terrain.ceilingPadding()) : 0; - int bottomExtension = forceCarve || bore ? Math.max(0, terrain.floorPadding()) : 0; - int bandMin = Math.max(worldMin, Math.min(placement.minHeight(), placement.maxHeight())); - int bandMax = Math.min(worldMax, Math.max(placement.minHeight(), placement.maxHeight())); - int minimumShift = Math.max(worldMin - (bounds[1] - bottomExtension), bandMin - baseY); - int maximumShift = Math.min(0, Math.min(worldMax - (bounds[4] + topExtension), bandMax - baseY)); - if (minimumShift > maximumShift) { - return null; - } - - Long2IntOpenHashMap surfaceHeights = new Long2IntOpenHashMap(); - surfaceHeights.defaultReturnValue(Integer.MIN_VALUE); - if (bore || forceCarve && carveShape == StructureCarveShape.BOX) { - maximumShift = resolveBurialEnvelopeShift( - engine, - bounds[0] - sideExtension, - bounds[3] + sideExtension, - bounds[2] - sideExtension, - bounds[5] + sideExtension, - bounds[4] + topExtension, - maximumShift, - surfaceHeights - ); - if (maximumShift == Integer.MIN_VALUE) { - return null; - } - } else { - for (PlacedStructurePiece piece : pieces) { - maximumShift = resolveBurialEnvelopeShift( - engine, - piece.getMinX() - sideExtension, - piece.getMaxX() + sideExtension, - piece.getMinZ() - sideExtension, - piece.getMaxZ() + sideExtension, - piece.getMaxY() + topExtension, - maximumShift, - surfaceHeights - ); - if (maximumShift == Integer.MIN_VALUE) { - return null; - } - } - } - return minimumShift > maximumShift ? null : maximumShift; - } - - private static int resolveBurialEnvelopeShift(Engine engine, int minX, int maxX, int minZ, int maxZ, - int envelopeTopY, int maximumShift, - Long2IntOpenHashMap surfaceHeights) { - for (int x = minX; x <= maxX; x++) { - for (int z = minZ; z <= maxZ; z++) { - long columnKey = ((long) x << 32) ^ (z & 0xffffffffL); - int surfaceY = surfaceHeights.get(columnKey); - if (surfaceY == Integer.MIN_VALUE) { - if (surfaceHeights.size() >= MAX_BURIAL_COLUMNS) { - return Integer.MIN_VALUE; - } - surfaceY = engine.getHeight(x, z, true) + engine.getMinHeight(); - surfaceHeights.put(columnKey, surfaceY); - } - int allowedTopY = surfaceY - UNDERGROUND_SURFACE_CLEARANCE; - maximumShift = Math.min(maximumShift, allowedTopY - envelopeTopY); - } - } - return maximumShift; - } - - static String selectStructureKey(StructurePlacement placement, RNG rng) { - if (placement == null || placement.structures().isEmpty()) { - return null; - } - return placement.structures().get(rng.nextInt(placement.structures().size())); - } - - static KList alignCavePieces( - KList pieces, - StructurePlacement placement, - int anchorY - ) { - StructureAnchorMode mode = placement.resolvedAnchor(); - if (!mode.isCave()) { - return pieces; - } - int[] bounds = computeBounds(pieces); - if (bounds == null) { - return pieces; - } - int targetY = switch (mode) { - case CAVE_FLOOR -> bounds[1]; - case CAVE_CEILING -> bounds[4]; - case CAVE_CENTER, CAVE_ANY -> bounds[1] + Math.floorDiv(bounds[4] - bounds[1], 2); - default -> anchorY; - }; - return shiftPieces(pieces, anchorY - targetY); - } - - private static KList alignSurfacePieces(KList pieces, - StructurePlacement placement, - IrisStructure structure, int baseY) { - if (placement.isAnchoredUnderground() || pieces.size() <= 1 - || structure.getPlaceMode().placeMode().has(PlaceTrait.FREE_HEIGHT)) { - return pieces; - } - int[] bounds = computeBounds(pieces); - return bounds == null ? pieces : shiftPieces(pieces, baseY - bounds[1]); - } - - static boolean hasExactY(StructurePlacement placement, IrisStructure structure, - KList pieces) { - return placement.isAnchoredUnderground() || pieces.size() > 1 - || structure.getPlaceMode().placeMode().has(PlaceTrait.FREE_HEIGHT); - } - - private static boolean fitsVerticalBounds(KList pieces, int worldMin, int worldMax) { - int[] bounds = computeBounds(pieces); - return bounds != null && fitsVerticalBounds(bounds, worldMin, worldMax); - } - - private static boolean fitsVerticalBounds(int[] bounds, int worldMin, int worldMax) { - return bounds[1] >= worldMin && bounds[4] <= worldMax; - } - - private static boolean fitsHorizontalBounds(KList pieces, int originX, int originZ, - int structureRadius) { - int[] bounds = computeBounds(pieces); - return bounds != null && fitsHorizontalBounds(bounds, originX, originZ, structureRadius); - } - - private static boolean fitsHorizontalBounds(int[] bounds, int originX, int originZ, int structureRadius) { - return bounds[0] >= originX - structureRadius && bounds[3] <= originX + structureRadius - && bounds[2] >= originZ - structureRadius && bounds[5] <= originZ + structureRadius; - } - - private static KList shiftPieces(KList pieces, int shiftY) { - KList shifted = new KList<>(); - for (PlacedStructurePiece piece : pieces) { - shifted.add(new PlacedStructurePiece( - piece.getPiece(), piece.getObject(), piece.getX(), piece.getY() + shiftY, piece.getZ(), piece.getRotation(), - piece.getMinX(), piece.getMinY() + shiftY, piece.getMinZ(), - piece.getMaxX(), piece.getMaxY() + shiftY, piece.getMaxZ())); - } - return shifted; - } - - private static int[] computeBounds(KList pieces) { - if (pieces == null || pieces.isEmpty()) { - return null; - } - int minX = Integer.MAX_VALUE; - int minY = Integer.MAX_VALUE; - int minZ = Integer.MAX_VALUE; - int maxX = Integer.MIN_VALUE; - int maxY = Integer.MIN_VALUE; - int maxZ = Integer.MIN_VALUE; - for (PlacedStructurePiece piece : pieces) { - minX = Math.min(minX, piece.getMinX()); - minY = Math.min(minY, piece.getMinY()); - minZ = Math.min(minZ, piece.getMinZ()); - maxX = Math.max(maxX, piece.getMaxX()); - maxY = Math.max(maxY, piece.getMaxY()); - maxZ = Math.max(maxZ, piece.getMaxZ()); - } - return new int[]{minX, minY, minZ, maxX, maxY, maxZ}; - } - - private static int randomInclusive(RNG rng, int minimum, int maximum) { - if (minimum == maximum) { - return minimum; - } - return minimum + rng.nextInt((maximum - minimum) + 1); - } - - private static PlacementCatalog collectPlacementCatalog(Engine engine, String key) { - Set randomSpread = new LinkedHashSet<>(); - List concentricRings = new ArrayList<>(); - boolean hasDensity = false; - for (StructurePlacement placement : index(engine).placements) { - if (!isSearchablePlacement(engine, placement) - || !matches(placement, key, engine.getData())) { - continue; - } - if (placement.distribution() == StructureDistribution.RANDOM_SPREAD) { - randomSpread.add(new RandomSpreadParameters( - Math.max(1, placement.spacing()), placement.separation(), - StructurePlacementGrid.placementSalt(placement))); - } else if (placement.distribution() == StructureDistribution.CONCENTRIC_RINGS) { - concentricRings.add(placement); - } else if (placement.distribution() == StructureDistribution.DENSITY) { - hasDensity = true; - } - } - return new PlacementCatalog(List.copyOf(randomSpread), List.copyOf(concentricRings), hasDensity); - } - - static boolean isSearchableDensityPlacement(Engine engine, StructurePlacement placement) { - return placement != null - && placement.distribution() == StructureDistribution.DENSITY - && isSearchablePlacement(engine, placement); - } - - static boolean isSearchablePlacement(Engine engine, StructurePlacement placement) { - if (engine == null || placement == null || engine.getHeight() <= 0) { - return false; - } - if (placement.distribution() == StructureDistribution.DENSITY - && !(placement.density() > 0.0)) { - return false; - } - long worldMin = (long) engine.getMinHeight() + (placement.isAnchoredUnderground() ? 1L : 0L); - long worldMax = (long) engine.getMinHeight() + engine.getHeight() - - (placement.resolvedAnchor().isCave() ? 2L : 1L); - if (worldMin > worldMax) { - return false; - } - long configuredMin = placement.isAnchoredUnderground() - ? Math.min(placement.minHeight(), placement.maxHeight()) - : placement.minHeight(); - long configuredMax = placement.isAnchoredUnderground() - ? Math.max(placement.minHeight(), placement.maxHeight()) - : placement.maxHeight(); - return configuredMin <= configuredMax && configuredMin <= worldMax && configuredMax >= worldMin; - } - - private static long blockDistanceSquared( - ResolvedStart resolved, int fromBlockX, int fromBlockZ) { - long dx = (long) resolved.originX() - fromBlockX; - long dz = (long) resolved.originZ() - fromBlockZ; - return distanceSquaredSaturated(dx, dz); - } - - static long chunkBlockDistanceSquaredLowerBound( - int chunkX, int chunkZ, int fromBlockX, int fromBlockZ) { - long minimumX = (long) chunkX << 4; - long minimumZ = (long) chunkZ << 4; - long dx = axisDistance(fromBlockX, minimumX, minimumX + 15L); - long dz = axisDistance(fromBlockZ, minimumZ, minimumZ + 15L); - return distanceSquaredSaturated(dx, dz); - } - - private static long axisDistance(long point, long minimum, long maximum) { - if (point < minimum) { - return minimum - point; - } - if (point > maximum) { - return point - maximum; - } - return 0L; - } - - private static long chunkDeltaBlockDistanceLowerBound(long chunkDelta) { - return chunkDelta <= 0L ? 0L : chunkDelta * 16L - 15L; - } - - private static long distanceSquaredSaturated(long dx, long dz) { - long xSquared = squareSaturated(dx); - long zSquared = squareSaturated(dz); - if (Long.MAX_VALUE - xSquared < zSquared) { - return Long.MAX_VALUE; - } - return xSquared + zSquared; - } - - private static long squareSaturated(long value) { - long absolute = Math.abs(value); - if (absolute > 3_037_000_499L) { - return Long.MAX_VALUE; - } - return absolute * absolute; - } - - private static LocateResult found(LocatedCandidate candidate) { - ResolvedStart resolved = candidate.resolved(); - return new LocateResult(LocateStatus.FOUND, resolved.originX(), resolved.baseY(), resolved.originZ()); - } - - static long cellRingDistanceLowerBound(int ring, int spacing, int pcx, int pcz, - int centerCellX, int centerCellZ) { - if (ring <= 0) { - return 0L; - } - int localX = pcx - (centerCellX * spacing); - int localZ = pcz - (centerCellZ * spacing); - long ringOffset = (long) ring * spacing; - long positiveX = ringOffset - localX; - long negativeX = ringOffset + localX - (spacing - 1L); - long positiveZ = ringOffset - localZ; - long negativeZ = ringOffset + localZ - (spacing - 1L); - return Math.min(Math.min(positiveX, negativeX), Math.min(positiveZ, negativeZ)); - } - - private static long chunkKey(int cx, int cz) { - return ((long) cx << 32) ^ (cz & 0xffffffffL); - } - - private record PlacementAnchor(int x, int y, int z) { - } - - private static boolean matches(StructurePlacement placement, String key, IrisData data) { - if (placement == null || key == null || data == null) { - return false; - } - String normalizedKey = normalize(key); - for (NativeStructureSource source : placement.nativeStructures()) { - if (source != null && normalize(source.structure()).equals(normalizedKey)) { - return true; - } - } - for (String structureKey : placement.structures()) { - if (structureKey == null || structureKey.isBlank()) { - continue; - } - IrisStructure structure = StructureResources.structure(data, structureKey); - if (structure == null) { - continue; - } - if (normalize(structureKey).equals(normalizedKey) - || normalize(structure.getLoadKey()).equals(normalizedKey) - || normalize(structure.getVanillaSource()).equals(normalizedKey)) { - return true; - } - } - return false; - } - - static boolean matchesResolved(ResolvedPlacement resolved, String key) { - String normalizedKey = normalize(key); - return normalize(resolved.structureKey()).equals(normalizedKey) - || normalize(resolved.structure().getLoadKey()).equals(normalizedKey) - || normalize(resolved.structure().getVanillaSource()).equals(normalizedKey); - } - - private static String normalize(String key) { - return key == null ? "" : key.toLowerCase(Locale.ROOT); - } - - private static PlacementIndex index(Engine engine) { - if (engine == null) { - return EMPTY_INDEX; - } - if (engine.getData() == null || engine.getDimension() == null) { - throw new IllegalStateException("Iris structure index requires a fully bound engine and dimension"); - } - return engine.getGeneration().state(PlacementIndex.class, IrisStructureLocator::build); - } - - private static LocatableIndex locatableIndex(Engine engine) { - if (engine == null) { - return EMPTY_LOCATABLE_INDEX; - } - return engine.getGeneration().state(LocatableIndex.class, IrisStructureLocator::buildLocatableIndex); - } - - private static LocatableIndex buildLocatableIndex(Engine engine) { - IrisData data = engine.getData(); - Set keys = new LinkedHashSet<>(); - Set normalizedKeys = new LinkedHashSet<>(); - Set editableKeys = new LinkedHashSet<>(); - Set normalizedEditableKeys = new LinkedHashSet<>(); - Set nativeKeys = new LinkedHashSet<>(); - Set normalizedNativeKeys = new LinkedHashSet<>(); - for (StructurePlacement placement : index(engine).placements) { - if (!isSearchablePlacement(engine, placement)) { - continue; - } - if (placement.hasNativeStructures()) { - for (NativeStructureSource source : placement.nativeStructures()) { - addLocatableKey(source.structure(), keys, normalizedKeys); - addLocatableKey(source.structure(), nativeKeys, normalizedNativeKeys); - } - continue; - } - for (String structureKey : placement.structures()) { - IrisStructure structure = StructureResources.structure(data, structureKey); - if (structure == null) { - throw new IllegalStateException( - "Iris structure placement references missing structure '" + structureKey + "'"); - } - addLocatableKey(structureKey, keys, normalizedKeys); - addLocatableKey(structureKey, editableKeys, normalizedEditableKeys); - addLocatableKey(structure.getLoadKey(), keys, normalizedKeys); - addLocatableKey(structure.getLoadKey(), editableKeys, normalizedEditableKeys); - addLocatableKey(structure.getVanillaSource(), keys, normalizedKeys); - addLocatableKey(structure.getVanillaSource(), editableKeys, normalizedEditableKeys); - } - } - return new LocatableIndex( - Collections.unmodifiableSet(keys), - Collections.unmodifiableSet(normalizedKeys), - Collections.unmodifiableSet(editableKeys), - Collections.unmodifiableSet(normalizedEditableKeys), - Collections.unmodifiableSet(nativeKeys), - Collections.unmodifiableSet(normalizedNativeKeys)); - } - - private static void addLocatableKey(String key, Set keys, Set normalizedKeys) { - if (key == null || key.isBlank()) { - return; - } - String trimmedKey = key.trim(); - keys.add(trimmedKey); - normalizedKeys.add(normalize(trimmedKey)); - } - - private static PlacementIndex build(Engine engine) { - IrisData data = engine.getData(); - ModuleLog log = IrisModuleHost.hostLog(); - Set loadKeys = new LinkedHashSet<>(); - Set normalizedLoadKeys = new LinkedHashSet<>(); - Set vanillaAliases = new LinkedHashSet<>(); - Set suppressedVanillaSources = new LinkedHashSet<>(); - List placements = new ArrayList<>(); - collect(StructurePlacementScope.placementsOf(engine.getDimension()), data, log, loadKeys, normalizedLoadKeys, vanillaAliases, - suppressedVanillaSources, placements, true); - KList regions = engine.getDimension().getAllRegions(engine); - if (regions != null) { - for (IrisRegion region : regions) { - collect(StructurePlacementScope.placementsOf(region), data, log, - loadKeys, normalizedLoadKeys, vanillaAliases, - suppressedVanillaSources, placements, false); - } - } - KList biomes = engine.getDimension().getReachableBiomes(engine); - if (biomes != null) { - for (IrisBiome biome : biomes) { - collect(StructurePlacementScope.placementsOf(biome), data, log, - loadKeys, normalizedLoadKeys, vanillaAliases, - suppressedVanillaSources, placements, false); - } - } - return new PlacementIndex( - Collections.unmodifiableSet(loadKeys), - Collections.unmodifiableSet(normalizedLoadKeys), - Collections.unmodifiableSet(vanillaAliases), - Collections.unmodifiableSet(suppressedVanillaSources), - nativeKeys(placements), - List.copyOf(placements)); - } - - private static Set nativeKeys(List placements) { - Set nativeKeys = new LinkedHashSet<>(); - for (StructurePlacement placement : placements) { - if (!placement.hasNativeStructures()) { - continue; - } - for (NativeStructureSource source : placement.nativeStructures()) { - if (source != null) { - nativeKeys.add(normalize(source.structure())); - } - } - } - return Collections.unmodifiableSet(nativeKeys); - } - - private static void collect(List source, IrisData data, ModuleLog log, Set loadKeys, - Set normalizedLoadKeys, Set vanillaAliases, - Set suppressedVanillaSources, - List placements, boolean allowNativeSuppression) { - for (StructurePlacement placement : source) { - if (placement == null) { - throw new IllegalStateException("Iris structure placement list contains a null placement"); - } - NativeStartPlanner.validateBackend(placement); - boolean replacesNative = NativeStructureSuppression.REPLACE_SOURCE == placement.nativeSuppression(); - if (replacesNative && !allowNativeSuppression) { - throw new IllegalStateException("REPLACE_SOURCE is only valid on dimension-level structure placements"); - } - if (placement.hasNativeStructures()) { - for (NativeStructureSource nativeStructure : placement.nativeStructures()) { - if (nativeStructure == null - || nativeStructure.structure() == null - || !NAMESPACED_RESOURCE_KEY.matcher(nativeStructure.structure()).matches()) { - throw new IllegalStateException("Native structure placement contains an invalid structure key"); - } - String sourceKey = nativeStructure.structure(); - loadKeys.add(sourceKey); - normalizedLoadKeys.add(normalize(sourceKey)); - vanillaAliases.add(normalize(sourceKey)); - if (replacesNative) { - suppressedVanillaSources.add(normalize(sourceKey)); - } - } - placements.add(placement); - continue; - } - for (String structureKey : placement.structures()) { - if (structureKey == null || structureKey.isBlank()) { - throw new IllegalStateException(replacesNative - ? "REPLACE_SOURCE contains a blank Iris structure reference" - : "Iris structure placement contains a blank structure reference"); - } - IrisStructure structure = StructureResources.structure(data, structureKey); - if (structure == null) { - throw new IllegalStateException((replacesNative - ? "REPLACE_SOURCE references missing Iris structure '" - : "Iris structure placement references missing structure '") - + structureKey + "'"); - } - loadKeys.add(structureKey); - normalizedLoadKeys.add(normalize(structureKey)); - if (structure.getLoadKey() != null && !structure.getLoadKey().isBlank()) { - loadKeys.add(structure.getLoadKey()); - normalizedLoadKeys.add(normalize(structure.getLoadKey())); - } - if (structure.getVanillaSource() != null && !structure.getVanillaSource().isBlank()) { - vanillaAliases.add(normalize(structure.getVanillaSource())); - } - if (replacesNative) { - String vanillaSource = structure.getVanillaSource(); - if (vanillaSource == null || !NAMESPACED_RESOURCE_KEY.matcher(vanillaSource).matches()) { - throw new IllegalStateException("REPLACE_SOURCE structure '" + structureKey - + "' must declare a valid namespaced vanillaSource"); - } - if (!StructureGraphCatalog.guaranteesRuntimeOutput(data, structure, log)) { - throw new IllegalStateException("REPLACE_SOURCE structure '" + structureKey - + "' is not runtime-viable; native generation will not be used as a fallback"); - } - suppressedVanillaSources.add(normalize(vanillaSource)); - } - } - placements.add(placement); - } - } - - public record ResolvedPlacement(StructurePlacement placement, String structureKey, IrisStructure structure, - KList pieces, RNG rng, - int originX, int baseY, int originZ, boolean exactY) { - } - - public enum LocateStatus { - FOUND, - NOT_FOUND, - SEARCH_LIMIT_REACHED - } - - public record LocateResult(LocateStatus status, int originX, int baseY, int originZ) { - public boolean found() { - return status == LocateStatus.FOUND; - } - } - - @FunctionalInterface - public interface CandidateFilter { - boolean accept(int chunkX, int chunkZ); - } - - public static final class CandidateSearchLimitException extends RuntimeException { - public CandidateSearchLimitException() { - super(null, null, false, false); - } - } - - private record RandomSpreadParameters(int spacing, int separation, int salt) { - } - - private record PlacementCatalog(List randomSpread, - List concentricRings, boolean hasDensity) { - } - - private record LocatableIndex(Set keys, Set normalizedKeys, - Set editableKeys, Set normalizedEditableKeys, - Set nativeKeys, Set normalizedNativeKeys) { - } - - private record ResolvedStart(int originX, int baseY, int originZ) { - } - - private record LocatedCandidate(ResolvedStart resolved, long distanceSquared) { - } - - private static final class CandidateBudget { - private int checked; - - private void claim() { - if (checked >= CANDIDATE_BUDGET) { - throw new CandidateSearchLimitException(); - } - checked++; - } - } - - private static final class PlacementIndex { - private final Set loadKeys; - private final Set normalizedLoadKeys; - private final Set vanillaAliases; - private final Set suppressedVanillaSources; - private final Set nativeKeys; - private final List placements; - - private PlacementIndex(Set loadKeys, Set normalizedLoadKeys, - Set vanillaAliases, Set suppressedVanillaSources, - Set nativeKeys, - List placements) { - this.loadKeys = loadKeys; - this.normalizedLoadKeys = normalizedLoadKeys; - this.vanillaAliases = vanillaAliases; - this.suppressedVanillaSources = suppressedVanillaSources; - this.nativeKeys = nativeKeys; - this.placements = placements; - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/PlacedObject.java b/src/main/java/art/arcane/iris/engine/framework/PlacedObject.java deleted file mode 100644 index ca294d0a2..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/PlacedObject.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.framework; - -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.prefab.IrisObject; -import lombok.AllArgsConstructor; -import lombok.Data; -import org.jetbrains.annotations.Nullable; - -@Data -@AllArgsConstructor -public class PlacedObject { - @Nullable - private IrisObjectPlacement placement; - @Nullable - private IrisObject object; - private int id; - private int xx; - private int zz; -} diff --git a/src/main/java/art/arcane/iris/engine/framework/PlacedStructurePiece.java b/src/main/java/art/arcane/iris/engine/framework/PlacedStructurePiece.java deleted file mode 100644 index 49d62339d..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/PlacedStructurePiece.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.framework; - -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectRotation; -import lombok.AllArgsConstructor; -import lombok.Data; - -@Data -@AllArgsConstructor -public class PlacedStructurePiece { - private final IrisJigsawPiece piece; - private final IrisObject object; - private final int x; - private final int y; - private final int z; - private final IrisObjectRotation rotation; - private final int minX; - private final int minY; - private final int minZ; - private final int maxX; - private final int maxY; - private final int maxZ; - - public boolean intersects(PlacedStructurePiece o) { - long maxExclusiveX = (long) maxX + 1L; - long maxExclusiveY = (long) maxY + 1L; - long maxExclusiveZ = (long) maxZ + 1L; - long otherMaxExclusiveX = (long) o.maxX + 1L; - long otherMaxExclusiveY = (long) o.maxY + 1L; - long otherMaxExclusiveZ = (long) o.maxZ + 1L; - return minX < otherMaxExclusiveX && maxExclusiveX > o.minX - && minY < otherMaxExclusiveY && maxExclusiveY > o.minY - && minZ < otherMaxExclusiveZ && maxExclusiveZ > o.minZ; - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/StructureAssembler.java b/src/main/java/art/arcane/iris/engine/framework/StructureAssembler.java deleted file mode 100644 index cef458cb6..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/StructureAssembler.java +++ /dev/null @@ -1,1358 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.framework; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.structure.CompiledStructureGraph; -import art.arcane.iris.engine.framework.structure.JigsawPoolSelection; -import art.arcane.iris.engine.framework.structure.PlanarJigsawWorkcellResolver; -import art.arcane.iris.engine.framework.structure.StructureAssemblyResult; -import art.arcane.iris.engine.framework.structure.StructureAssemblyStatus; -import art.arcane.iris.engine.framework.structure.StructureGraphCatalog; -import art.arcane.iris.engine.framework.structure.StructureGraphCompilation; -import art.arcane.iris.engine.framework.structure.StructureGraphCompiler; -import art.arcane.iris.engine.framework.structure.StructureGraphDiagnostic; -import art.arcane.iris.engine.framework.structure.StructureGraphResolver; -import art.arcane.iris.engine.object.value.IrisDirection; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawMode; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectRotation; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; - -import com.volmit.ModuleLog; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Deque; -import java.util.HashMap; -import java.util.IdentityHashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -public final class StructureAssembler { - private static final int HARD_PIECE_CAP = 512; - private static final int MAX_DEPTH = 30; - private static final int MAX_SIZE_CHUNKS = 32; - private static final int[] NO_ROTATION = {0}; - private static final int[] Y_DEGREES = {0, 90, 180, 270}; - - private final StructureGraphResolver resolver; - private final CompiledStructureGraph graph; - private final IrisStructure structure; - private final int originX; - private final int originY; - private final int originZ; - private final int radius; - private final Map - planarWorkcells; - - private StructureAssembler(AssemblyOptions options) { - this.resolver = options.resolver(); - this.graph = options.graph(); - this.structure = options.structure(); - this.originX = options.origin().getX(); - this.originY = options.origin().getY(); - this.originZ = options.origin().getZ(); - this.planarWorkcells = this.structure.resolvedMode() == IrisJigsawMode.PLANAR_JIGSAW - ? PlanarJigsawWorkcellResolver.resolve(this.structure) - : Map.of(); - this.radius = this.structure.getMaxSizeChunks() >= 1 - && this.structure.getMaxSizeChunks() <= MAX_SIZE_CHUNKS - ? this.structure.getMaxSizeChunks() * 16 : 0; - } - - public static StructureAssembler forData(IrisData data, IrisStructure structure, IrisPosition origin, ModuleLog log) { - IrisData activeData = Objects.requireNonNull(data, "Structure assembly data must not be null"); - IrisStructure activeStructure = Objects.requireNonNull( - structure, "Structure assembly structure must not be null"); - return forCompilation(StructureGraphCatalog.compile(activeData, activeStructure, log), origin); - } - - public static StructureAssembler forResolver(StructureGraphResolver resolver, IrisStructure structure, - IrisPosition origin) { - StructureGraphResolver activeResolver = Objects.requireNonNull( - resolver, "Structure assembly resolver must not be null"); - IrisStructure activeStructure = Objects.requireNonNull( - structure, "Structure assembly structure must not be null"); - return forCompilation(StructureGraphCompiler.compile(activeStructure, activeResolver), origin); - } - - public static StructureAssembler forCompilation(StructureGraphCompilation compilation, IrisPosition origin) { - StructureGraphCompilation activeCompilation = Objects.requireNonNull( - compilation, "Structure graph compilation must not be null"); - if (activeCompilation.hasErrors()) { - throw invalidGraph(activeCompilation); - } - return new StructureAssembler(new AssemblyOptions( - StructureGraphResolver.forCompiledGraph(activeCompilation.getGraph()), - activeCompilation.getGraph(), activeCompilation.getGraph().getStructure(), origin)); - } - - public StructureAssemblyResult assemble(RNG rng) { - Objects.requireNonNull(rng, "Structure assembly RNG must not be null"); - if (radius == 0) { - throw new IllegalStateException("Structure '" + structure.getLoadKey() - + "' has maxSizeChunks outside 1.." + MAX_SIZE_CHUNKS); - } - if (structure.getMaxDepth() < 1 || structure.getMaxDepth() > MAX_DEPTH) { - throw new IllegalStateException("Structure '" + structure.getLoadKey() - + "' has maxDepth outside 1.." + MAX_DEPTH); - } - String startPoolKey = normalize(structure.getStartPool()); - IrisJigsawPool startPool = resolver.loadPool(startPoolKey); - if (startPool == null || startPool.getPieces() == null || startPool.getPieces().isEmpty()) { - throw new IllegalStateException("Structure '" + structure.getLoadKey() - + "' has no resolvable start pool '" + startPoolKey + "'"); - } - - KList placed = new KList<>(); - Deque pending = new ArrayDeque<>(); - Map placementCounts = new HashMap<>(); - Map> consumedConnectors = new IdentityHashMap<>(); - Map> openConnectors = - new IdentityHashMap<>(); - String selectedTheme = JigsawPoolSelection.selectTheme(structure, rng); - - List eligibleStartEntries = eligibleEntries( - startPool, selectedTheme, 0, placementCounts, true, false); - if (eligibleStartEntries.isEmpty()) { - return StructureAssemblyResult.failed( - StructureAssemblyStatus.FAILED_RULES, - placed, - selectedTheme, - "The start pool has no entry eligible for theme '" + themeLabel(selectedTheme) - + "' at depth zero"); - } - List startEntries = chanceEligibleEntries(eligibleStartEntries, rng); - if (startEntries.isEmpty()) { - return StructureAssemblyResult.intentionalEmpty( - selectedTheme, - "No start-pool membership passed its chance gate"); - } - IrisJigsawPieceEntry startEntry = weightedPick(startEntries, rng); - if (startEntry == null) { - throw new IllegalStateException("Structure '" + structure.getLoadKey() - + "' start pool has no positively weighted entry"); - } - if (startEntry.isEmpty()) { - return StructureAssemblyResult.intentionalEmpty( - selectedTheme, - "The selected start-pool membership intentionally produces no structure"); - } - String startPieceKey = normalize(startEntry.getPiece()); - IrisJigsawPiece startPiece = resolver.loadPiece(startPieceKey); - if (startPiece == null) { - throw new IllegalStateException("Structure '" + structure.getLoadKey() - + "' start pool references missing piece '" + startPieceKey + "'"); - } - String startObjectKey = normalize(startPiece.getObject()); - IrisObject startObject = resolver.loadObject(startObjectKey); - if (startObject == null) { - throw new IllegalStateException("Structure '" + structure.getLoadKey() - + "' start piece references missing object '" + startObjectKey + "'"); - } - if (startPiece.getConnectors() == null) { - throw new IllegalStateException("Structure '" + structure.getLoadKey() - + "' start piece has no connector list"); - } - - int startRotY = startPiece.isRotatable() ? Y_DEGREES[rng.i(Y_DEGREES.length)] : 0; - IrisObjectRotation startRot = IrisObjectRotation.of(0, startRotY, 0); - PlacedStructurePiece start = build(startPiece, startObject, originX, originY, originZ, startRot); - placed.add(start); - registerPlacedPiece(consumedConnectors, start, null); - incrementPlacement(placementCounts, startPieceKey); - if (!startPiece.resolvedRules().isTerminal()) { - enqueuePieceExpansion(pending, openConnectors, start, startObject, 0, 1, null, 0); - } - - while (!pending.isEmpty()) { - PieceExpansion expansion = removeNextPieceExpansion(pending); - for (OpenConnector connector : expansion.connectors()) { - if (isConsumed(consumedConnectors, connector)) { - continue; - } - if (placed.size() >= HARD_PIECE_CAP) { - return StructureAssemblyResult.failed( - StructureAssemblyStatus.HARD_CAP, - placed, - selectedTheme, - "Exceeded the hard piece cap of " + HARD_PIECE_CAP - + " with queued piece expansions unresolved"); - } - int depth = connector.depth; - if (depth > structure.getMaxDepth()) { - continue; - } - - IrisJigsawPool pool = resolver.loadPool(connector.pool); - if (pool == null) { - throw new IllegalStateException("Structure '" + structure.getLoadKey() - + "' references missing connector pool '" + connector.pool + "'"); - } - - AttachmentResult attachment = attachOne( - pending, - placed, - placementCounts, - consumedConnectors, - openConnectors, - pool, - connector, - depth, - selectedTheme, - rng); - consume(consumedConnectors, connector.sourcePiece(), connector.sourceConnector()); - if (attachment.state() == AttachmentState.FAILED) { - return StructureAssemblyResult.failed( - StructureAssemblyStatus.FAILED_UNCAPPED, - placed, - selectedTheme, - attachment.detail()); - } - } - } - String unsatisfiedRule = unsatisfiedMinimumPlacement(placementCounts, selectedTheme); - if (!unsatisfiedRule.isEmpty()) { - return StructureAssemblyResult.failed( - StructureAssemblyStatus.FAILED_RULES, - placed, - selectedTheme, - unsatisfiedRule); - } - return StructureAssemblyResult.complete(placed, selectedTheme); - } - - private AttachmentResult attachOne( - Deque pending, - KList placed, - Map placementCounts, - Map> consumedConnectors, - Map> openConnectors, - IrisJigsawPool pool, - OpenConnector connector, - int depth, - String selectedTheme, - RNG rng - ) { - if (pool.getPieces() == null) { - throw assemblyFailure("connector pool '" + connector.pool + "' has no piece list"); - } - if (closeAgainstPlacedNeighbor(placed, consumedConnectors, connector)) { - return AttachmentResult.success(AttachmentState.CLOSED); - } - boolean fallbackRequired = pool.requiresFallback(structure.isRequireCaps()); - if (depth < structure.getMaxDepth() && !pool.getPieces().isEmpty()) { - AttachmentState primary = attachFromPool( - pending, - placed, - placementCounts, - consumedConnectors, - openConnectors, - pool, - connector, - selectedTheme, - false, - !fallbackRequired, - rng); - if (primary != AttachmentState.NO_MATCH) { - return AttachmentResult.success(primary); - } - } else if (pool.getPieces().isEmpty() && !fallbackRequired) { - return AttachmentResult.success(AttachmentState.TERMINATED); - } - String fallbackKey = JigsawPoolSelection.directFallbackKey(pool); - if (fallbackKey.isEmpty()) { - if (branchFailureRequiresAssemblyFailure(fallbackRequired, depth)) { - return AttachmentResult.failed( - "Connector pool '" + connector.pool - + "' could not place a piece and has no direct fallback at " - + connectorLocation(connector)); - } - return AttachmentResult.success(AttachmentState.TERMINATED); - } - IrisJigsawPool fallback = resolver.loadPool(fallbackKey); - if (fallback == null) { - throw assemblyFailure("references missing authored fallback pool '" + fallbackKey + "'"); - } - if (fallback.getPieces() == null) { - throw assemblyFailure("authored fallback pool '" + fallbackKey + "' has no piece list"); - } - if (fallback.getPieces().isEmpty()) { - return fallbackRequired - ? AttachmentResult.failed( - "Required fallback pool '" + fallbackKey + "' has no physical terminal piece") - : AttachmentResult.success(AttachmentState.TERMINATED); - } - AttachmentState fallbackState = attachFromPool( - pending, - placed, - placementCounts, - consumedConnectors, - openConnectors, - fallback, - connector, - selectedTheme, - fallbackRequired, - !fallbackRequired, - rng); - if (fallbackState != AttachmentState.NO_MATCH) { - return AttachmentResult.success(fallbackState); - } - if (branchFailureRequiresAssemblyFailure(fallbackRequired, depth)) { - return AttachmentResult.failed( - "Direct fallback pool '" + fallbackKey + "' could not place" - + (fallbackRequired ? " a required terminal piece" : " a compatible piece") - + " at " + connectorLocation(connector)); - } - return AttachmentResult.success(AttachmentState.TERMINATED); - } - - private boolean branchFailureRequiresAssemblyFailure(boolean fallbackRequired, int depth) { - return fallbackRequired - || depth < structure.getMaxDepth() - && structure.resolvedBranchFailurePolicy() == IrisJigsawBranchFailurePolicy.FAIL_ASSEMBLY; - } - - private AttachmentState attachFromPool( - Deque pending, - KList placed, - Map placementCounts, - Map> consumedConnectors, - Map> openConnectors, - IrisJigsawPool pool, - OpenConnector connector, - String selectedTheme, - boolean terminalOnly, - boolean allowEmpty, - RNG rng - ) { - int ruleDepth = Math.min(connector.pieceDepth, structure.getMaxDepth()); - for (IrisJigsawPieceEntry entry : weightedOrder( - pool, - selectedTheme, - ruleDepth, - placementCounts, - allowEmpty, - terminalOnly, - rng)) { - if (entry.isEmpty()) { - return AttachmentState.TERMINATED; - } - String pieceName = normalize(entry.getPiece()); - if (pieceName.isEmpty()) { - throw assemblyFailure("pool contains a weighted entry without a piece key"); - } - IrisJigsawPiece piece = resolver.loadPiece(pieceName); - if (piece == null) { - throw assemblyFailure("pool references missing piece '" + pieceName + "'"); - } - String objectKey = normalize(piece.getObject()); - if (objectKey.isEmpty()) { - throw assemblyFailure("piece '" + pieceName + "' has no object key"); - } - IrisObject object = resolver.loadObject(objectKey); - if (object == null) { - throw assemblyFailure("piece '" + pieceName + "' references missing object '" - + objectKey + "'"); - } - if (piece.getConnectors() == null) { - throw assemblyFailure("piece '" + pieceName + "' has no connector list"); - } - - for (IrisJigsawConnector pieceConnector : piece.getConnectors()) { - requireConnector(pieceConnector, pieceName); - } - List candidateConnectors = orderedConnectors(piece.getConnectors(), null); - for (IrisJigsawConnector cb : candidateConnectors) { - if (connector.targetName == null) { - throw assemblyFailure("open connector from pool '" + connector.pool + "' has no target name"); - } - if (!Objects.equals(connector.channel, cb.getChannel())) { - continue; - } - if (!cb.getName().equals(connector.targetName)) { - continue; - } - - IrisDirection needed = connector.facing.reverse(); - int[] rotations = piece.isRotatable() ? rotationCandidates(connector.joint, rng) : NO_ROTATION; - for (int yDeg : rotations) { - IrisObjectRotation rot = IrisObjectRotation.of(0, yDeg, 0); - IrisDirection rotatedFace = rot.rotate(cb.getDirection()); - if (rotatedFace != needed) { - continue; - } - if (connector.joint == JigsawJoint.ALIGNED && rot.rotate(cb.getTop()) != connector.top) { - continue; - } - - IrisPosition rcr = connectorOffset(object, cb, rot); - int wcx = connector.wx + connector.facing.x(); - int wcy = connector.wy + connector.facing.y(); - int wcz = connector.wz + connector.facing.z(); - int px = wcx - rcr.getX(); - int py = wcy - rcr.getY(); - int pz = wcz - rcr.getZ(); - - PlacedStructurePiece candidate = build(piece, object, px, py, pz, rot); - if (!withinRadius(candidate) || collides(placed, candidate)) { - continue; - } - List closures = requiredClosures( - placed, - consumedConnectors, - connector, - candidate, - cb); - if (closures == null) { - continue; - } - if (!capReservationsRemainViable( - placed, - placementCounts, - consumedConnectors, - openConnectors, - connector, - candidate, - cb, - closures, - pieceName, - selectedTheme)) { - continue; - } - - placed.add(candidate); - registerPlacedPiece(consumedConnectors, candidate, cb); - for (ConnectorClosure closure : closures) { - consume(consumedConnectors, closure.existingPiece(), closure.existingConnector()); - consume(consumedConnectors, candidate, closure.candidateConnector()); - } - incrementPlacement(placementCounts, pieceName); - if (!piece.resolvedRules().isTerminal() && connector.depth < structure.getMaxDepth()) { - enqueuePieceExpansion( - pending, - openConnectors, - candidate, - object, - connector.depth + 1, - connector.pieceDepth + 1, - cb, - connector.placementPriority); - } - return AttachmentState.ATTACHED; - } - } - } - return AttachmentState.NO_MATCH; - } - - private boolean closeAgainstPlacedNeighbor( - KList placed, - Map> consumedConnectors, - OpenConnector source - ) { - int targetX = source.wx() + source.facing().x(); - int targetY = source.wy() + source.facing().y(); - int targetZ = source.wz() + source.facing().z(); - for (PlacedStructurePiece candidatePiece : placed) { - if (candidatePiece == source.sourcePiece() || candidatePiece.getPiece().getConnectors() == null) { - continue; - } - for (IrisJigsawConnector candidate : candidatePiece.getPiece().getConnectors()) { - if (isConsumed(consumedConnectors, candidatePiece, candidate) - || !existingConnectorMatches(source, candidatePiece, candidate, - targetX, targetY, targetZ)) { - continue; - } - consume(consumedConnectors, candidatePiece, candidate); - return true; - } - } - return false; - } - - private List requiredClosures( - KList placed, - Map> consumedConnectors, - OpenConnector attachmentSource, - PlacedStructurePiece candidatePiece, - IrisJigsawConnector attachmentConnector - ) { - if (!structure.isRequireCaps()) { - return List.of(); - } - List closures = new ArrayList<>(); - Set matchedCandidate = Collections.newSetFromMap(new IdentityHashMap<>()); - Map> matchedExisting = new IdentityHashMap<>(); - matchedCandidate.add(attachmentConnector); - matchedExisting.computeIfAbsent( - attachmentSource.sourcePiece(), - ignored -> Collections.newSetFromMap(new IdentityHashMap<>())) - .add(attachmentSource.sourceConnector()); - - for (PlacedStructurePiece existingPiece : placed) { - for (IrisJigsawConnector existingConnector : existingPiece.getPiece().getConnectors()) { - if (normalize(existingConnector.getPool()).isEmpty() - || isConsumed(consumedConnectors, existingPiece, existingConnector) - || isMatched(matchedExisting, existingPiece, existingConnector)) { - continue; - } - IrisPosition target = connectorTarget(existingPiece, existingConnector); - if (!contains(candidatePiece, target)) { - continue; - } - IrisJigsawConnector matchingCandidate = matchingConnector( - existingPiece, - existingConnector, - candidatePiece, - matchedCandidate); - if (matchingCandidate == null) { - return null; - } - matchedCandidate.add(matchingCandidate); - matchedExisting.computeIfAbsent( - existingPiece, - ignored -> Collections.newSetFromMap(new IdentityHashMap<>())) - .add(existingConnector); - closures.add(new ConnectorClosure(existingPiece, existingConnector, matchingCandidate)); - } - } - - if (candidatePiece.getPiece().resolvedRules().isTerminal()) { - return closures; - } - for (IrisJigsawConnector candidateConnector : candidatePiece.getPiece().getConnectors()) { - if (matchedCandidate.contains(candidateConnector) - || normalize(candidateConnector.getPool()).isEmpty()) { - continue; - } - IrisPosition target = connectorTarget(candidatePiece, candidateConnector); - PlacedStructurePiece occupied = containingPiece(placed, target); - if (occupied == null) { - continue; - } - Set unavailable = matchedExisting.getOrDefault(occupied, Set.of()); - IrisJigsawConnector matchingExisting = matchingConnector( - candidatePiece, - candidateConnector, - occupied, - unavailable); - if (matchingExisting == null - || isConsumed(consumedConnectors, occupied, matchingExisting)) { - return null; - } - matchedCandidate.add(candidateConnector); - matchedExisting.computeIfAbsent( - occupied, - ignored -> Collections.newSetFromMap(new IdentityHashMap<>())) - .add(matchingExisting); - closures.add(new ConnectorClosure(occupied, matchingExisting, candidateConnector)); - } - return closures; - } - - private boolean capReservationsRemainViable( - KList placed, - Map placementCounts, - Map> consumedConnectors, - Map> openConnectors, - OpenConnector attachmentSource, - PlacedStructurePiece candidatePiece, - IrisJigsawConnector attachmentConnector, - List closures, - String candidatePieceKey, - String selectedTheme - ) { - if (!structure.isRequireCaps() || structure.resolvedMode() != IrisJigsawMode.PLANAR_JIGSAW) { - return true; - } - List unresolved = new ArrayList<>(); - for (PlacedStructurePiece placedPiece : placed) { - Map definitions = openConnectors.get(placedPiece); - if (definitions == null) { - continue; - } - for (IrisJigsawConnector connector : placedPiece.getPiece().getConnectors()) { - OpenConnector open = definitions.get(connector); - if (open == null - || isConsumed(consumedConnectors, placedPiece, connector) - || connectorWillBeConsumed( - placedPiece, connector, attachmentSource, candidatePiece, attachmentConnector, closures)) { - continue; - } - unresolved.add(open); - } - } - if (!candidatePiece.getPiece().resolvedRules().isTerminal() - && attachmentSource.depth() < structure.getMaxDepth()) { - for (IrisJigsawConnector connector : candidatePiece.getPiece().getConnectors()) { - if (normalize(connector.getPool()).isEmpty() - || connectorWillBeConsumed( - candidatePiece, connector, attachmentSource, candidatePiece, attachmentConnector, closures)) { - continue; - } - unresolved.add(openConnector( - candidatePiece, - candidatePiece.getObject(), - connector, - attachmentSource.depth() + 1, - attachmentSource.pieceDepth() + 1)); - } - } - - List occupied = new ArrayList<>(placed.size() + unresolved.size() + 1); - occupied.addAll(placed); - occupied.add(candidatePiece); - Map reservedCounts = new HashMap<>(placementCounts); - incrementPlacement(reservedCounts, candidatePieceKey); - for (OpenConnector open : unresolved) { - CapReservation reservation = reserveTerminalCap( - open, - occupied, - reservedCounts, - selectedTheme); - if (reservation == null) { - return false; - } - occupied.add(reservation.piece()); - incrementPlacement(reservedCounts, reservation.pieceKey()); - } - return true; - } - - private boolean connectorWillBeConsumed( - PlacedStructurePiece piece, - IrisJigsawConnector connector, - OpenConnector attachmentSource, - PlacedStructurePiece candidatePiece, - IrisJigsawConnector attachmentConnector, - List closures - ) { - if (piece == attachmentSource.sourcePiece() && connector == attachmentSource.sourceConnector() - || piece == candidatePiece && connector == attachmentConnector - || piece == candidatePiece && candidatePiece.getPiece().resolvedRules().isTerminal()) { - return true; - } - for (ConnectorClosure closure : closures) { - if (piece == closure.existingPiece() && connector == closure.existingConnector() - || piece == candidatePiece && connector == closure.candidateConnector()) { - return true; - } - } - return false; - } - - private CapReservation reserveTerminalCap( - OpenConnector source, - List occupied, - Map placementCounts, - String selectedTheme - ) { - IrisJigsawPool sourcePool = resolver.loadPool(source.pool()); - if (sourcePool == null) { - return null; - } - String fallbackKey = JigsawPoolSelection.directFallbackKey(sourcePool); - if (fallbackKey.isEmpty()) { - return null; - } - IrisJigsawPool fallback = resolver.loadPool(fallbackKey); - if (fallback == null || fallback.getPieces() == null) { - return null; - } - int ruleDepth = Math.min(source.pieceDepth(), structure.getMaxDepth()); - for (IrisJigsawPieceEntry entry : eligibleEntries( - fallback, - selectedTheme, - ruleDepth, - placementCounts, - false, - true)) { - if (entry.isEmpty() || entry.getChance() <= 0D) { - continue; - } - String pieceKey = normalize(entry.getPiece()); - IrisJigsawPiece piece = resolver.loadPiece(pieceKey); - if (piece == null || piece.getConnectors() == null) { - continue; - } - IrisObject object = resolver.loadObject(normalize(piece.getObject())); - if (object == null) { - continue; - } - for (IrisJigsawConnector connector : orderedConnectors(piece.getConnectors(), null)) { - if (!Objects.equals(source.channel(), connector.getChannel()) - || !Objects.equals(source.targetName(), connector.getName())) { - continue; - } - int[] rotations = piece.isRotatable() ? Y_DEGREES : NO_ROTATION; - for (int yDegrees : rotations) { - IrisObjectRotation rotation = IrisObjectRotation.of(0, yDegrees, 0); - if (rotation.rotate(connector.getDirection()) != source.facing().reverse() - || source.joint() == JigsawJoint.ALIGNED - && rotation.rotate(connector.getTop()) != source.top()) { - continue; - } - IrisPosition offset = connectorOffset(object, connector, rotation); - int logicalX = source.wx() + source.facing().x() - offset.getX(); - int logicalY = source.wy() + source.facing().y() - offset.getY(); - int logicalZ = source.wz() + source.facing().z() - offset.getZ(); - PlacedStructurePiece reservation = build( - piece, - object, - logicalX, - logicalY, - logicalZ, - rotation); - if (withinRadius(reservation) && !collides(occupied, reservation)) { - return new CapReservation(pieceKey, reservation); - } - } - } - } - return null; - } - - private IrisJigsawConnector matchingConnector( - PlacedStructurePiece sourcePiece, - IrisJigsawConnector sourceConnector, - PlacedStructurePiece targetPiece, - Set unavailable - ) { - IrisPosition target = connectorTarget(sourcePiece, sourceConnector); - IrisDirection sourceFacing = sourcePiece.getRotation().rotate(sourceConnector.getDirection()); - IrisDirection sourceTop = sourcePiece.getRotation().rotate(sourceConnector.getTop()); - for (IrisJigsawConnector candidate : targetPiece.getPiece().getConnectors()) { - if (unavailable.contains(candidate) - || !Objects.equals(sourceConnector.getChannel(), candidate.getChannel()) - || !Objects.equals(sourceConnector.getTargetName(), candidate.getName())) { - continue; - } - IrisPosition candidatePosition = connectorPosition(targetPiece, candidate); - if (!target.equals(candidatePosition) - || targetPiece.getRotation().rotate(candidate.getDirection()) != sourceFacing.reverse()) { - continue; - } - if (sourceConnector.getJoint() != JigsawJoint.ALIGNED - || targetPiece.getRotation().rotate(candidate.getTop()) == sourceTop) { - return candidate; - } - } - return null; - } - - private IrisPosition connectorPosition(PlacedStructurePiece piece, IrisJigsawConnector connector) { - IrisPosition center = logicalCenter(piece); - IrisPosition offset = connectorOffset(piece.getObject(), connector, piece.getRotation()); - return new IrisPosition( - center.getX() + offset.getX(), - center.getY() + offset.getY(), - center.getZ() + offset.getZ()); - } - - private IrisPosition connectorTarget(PlacedStructurePiece piece, IrisJigsawConnector connector) { - IrisPosition position = connectorPosition(piece, connector); - IrisDirection facing = piece.getRotation().rotate(connector.getDirection()); - return new IrisPosition( - position.getX() + facing.x(), - position.getY() + facing.y(), - position.getZ() + facing.z()); - } - - private PlacedStructurePiece containingPiece( - KList pieces, - IrisPosition position - ) { - for (PlacedStructurePiece piece : pieces) { - if (contains(piece, position)) { - return piece; - } - } - return null; - } - - private boolean contains(PlacedStructurePiece piece, IrisPosition position) { - return position.getX() >= piece.getMinX() && position.getX() <= piece.getMaxX() - && position.getY() >= piece.getMinY() && position.getY() <= piece.getMaxY() - && position.getZ() >= piece.getMinZ() && position.getZ() <= piece.getMaxZ(); - } - - private boolean isMatched( - Map> matched, - PlacedStructurePiece piece, - IrisJigsawConnector connector - ) { - Set connectors = matched.get(piece); - return connectors != null && connectors.contains(connector); - } - - private boolean existingConnectorMatches( - OpenConnector source, - PlacedStructurePiece candidatePiece, - IrisJigsawConnector candidate, - int targetX, - int targetY, - int targetZ - ) { - requireConnector(candidate, candidatePiece.getObject().getLoadKey()); - if (!Objects.equals(source.channel(), candidate.getChannel()) - || !Objects.equals(source.targetName(), candidate.getName())) { - return false; - } - IrisPosition rotated = connectorOffset( - candidatePiece.getObject(), candidate, candidatePiece.getRotation()); - IrisPosition center = logicalCenter(candidatePiece); - if (center.getX() + rotated.getX() != targetX - || center.getY() + rotated.getY() != targetY - || center.getZ() + rotated.getZ() != targetZ) { - return false; - } - if (candidatePiece.getRotation().rotate(candidate.getDirection()) != source.facing().reverse()) { - return false; - } - return source.joint() != JigsawJoint.ALIGNED - || candidatePiece.getRotation().rotate(candidate.getTop()) == source.top(); - } - - private void registerPlacedPiece( - Map> consumedConnectors, - PlacedStructurePiece piece, - IrisJigsawConnector attachment - ) { - Set consumed = Collections.newSetFromMap(new IdentityHashMap<>()); - if (piece.getPiece().resolvedRules().isTerminal()) { - consumed.addAll(piece.getPiece().getConnectors()); - } else if (attachment != null) { - consumed.add(attachment); - } - consumedConnectors.put(piece, consumed); - } - - private boolean isConsumed( - Map> consumedConnectors, - OpenConnector connector - ) { - return isConsumed(consumedConnectors, connector.sourcePiece(), connector.sourceConnector()); - } - - private boolean isConsumed( - Map> consumedConnectors, - PlacedStructurePiece piece, - IrisJigsawConnector connector - ) { - Set consumed = consumedConnectors.get(piece); - return consumed != null && consumed.contains(connector); - } - - private void consume( - Map> consumedConnectors, - PlacedStructurePiece piece, - IrisJigsawConnector connector - ) { - Set consumed = consumedConnectors.get(piece); - if (consumed == null) { - throw assemblyFailure("placed piece connector ownership was not registered"); - } - consumed.add(connector); - } - - private void enqueuePieceExpansion( - Deque pending, - Map> openConnectors, - PlacedStructurePiece p, - IrisObject object, int depth, int pieceDepth, IrisJigsawConnector skip, - int placementPriority) { - if (p.getPiece().getConnectors() == null) { - throw assemblyFailure("placed piece for object '" + object.getLoadKey() + "' has no connector list"); - } - List connectors = new ArrayList<>(); - Map definitions = new IdentityHashMap<>(); - for (IrisJigsawConnector con : orderedConnectors(p.getPiece().getConnectors(), skip)) { - requireConnector(con, object.getLoadKey()); - if (con.getPool() == null || con.getPool().isBlank()) { - continue; - } - OpenConnector openConnector = openConnector(p, object, con, depth, pieceDepth); - connectors.add(openConnector); - definitions.put(con, openConnector); - } - openConnectors.put(p, definitions); - if (!connectors.isEmpty()) { - pending.addLast(new PieceExpansion(connectors, placementPriority)); - } - } - - private OpenConnector openConnector( - PlacedStructurePiece piece, - IrisObject object, - IrisJigsawConnector connector, - int depth, - int pieceDepth - ) { - IrisPosition offset = connectorOffset(object, connector, piece.getRotation()); - IrisPosition center = logicalCenter(piece); - return new OpenConnector( - piece, - connector, - center.getX() + offset.getX(), - center.getY() + offset.getY(), - center.getZ() + offset.getZ(), - piece.getRotation().rotate(connector.getDirection()), - piece.getRotation().rotate(connector.getTop()), - normalize(connector.getPool()), - connector.getName(), - connector.getTargetName(), - connector.getChannel(), - connector.getJoint(), - depth, - pieceDepth, - connector.getPlacementPriority()); - } - - private List orderedConnectors(List connectors, - IrisJigsawConnector skip) { - List ordered = new ArrayList<>(connectors.size()); - for (IrisJigsawConnector connector : connectors) { - if (connector != skip) { - ordered.add(connector); - } - } - ordered.sort((first, second) -> Integer.compare( - second.getSelectionPriority(), first.getSelectionPriority())); - return ordered; - } - - private PieceExpansion removeNextPieceExpansion(Deque pending) { - int highestPriority = Integer.MIN_VALUE; - for (PieceExpansion expansion : pending) { - highestPriority = Math.max(highestPriority, expansion.placementPriority()); - } - Iterator iterator = pending.iterator(); - while (iterator.hasNext()) { - PieceExpansion expansion = iterator.next(); - if (expansion.placementPriority() == highestPriority) { - iterator.remove(); - return expansion; - } - } - throw assemblyFailure("piece expansion queue was unexpectedly empty"); - } - - private PlacedStructurePiece build(IrisJigsawPiece piece, IrisObject object, int x, int y, int z, IrisObjectRotation rot) { - int width = Math.max(1, object.getW()); - int height = Math.max(1, object.getH()); - int depth = Math.max(1, object.getD()); - if (structure.resolvedMode() == IrisJigsawMode.PLANAR_JIGSAW) { - IrisPosition dimensions = rotatedDimensions(object, rot); - IrisPosition offset = planarPlacementOffset(object, rot); - int minX = x - dimensions.getX() / 2; - int minY = y - dimensions.getY() / 2; - int minZ = z - dimensions.getZ() / 2; - return new PlacedStructurePiece( - piece, - object, - x + offset.getX(), - y + offset.getY(), - z + offset.getZ(), - rot, - minX, - minY, - minZ, - minX + dimensions.getX() - 1, - minY + dimensions.getY() - 1, - minZ + dimensions.getZ() - 1); - } - int localMinX = -(width / 2); - int localMinY = -(height / 2); - int localMinZ = -(depth / 2); - int localMaxX = localMinX + width - 1; - int localMaxY = localMinY + height - 1; - int localMaxZ = localMinZ + depth - 1; - IrisPosition rotatedMin = rot.rotate(new IrisPosition(localMinX, localMinY, localMinZ), 0, 0, 0); - IrisPosition rotatedMax = rot.rotate(new IrisPosition(localMaxX, localMaxY, localMaxZ), 0, 0, 0); - int minX = Math.min(rotatedMin.getX(), rotatedMax.getX()); - int minY = Math.min(rotatedMin.getY(), rotatedMax.getY()); - int minZ = Math.min(rotatedMin.getZ(), rotatedMax.getZ()); - int maxX = Math.max(rotatedMin.getX(), rotatedMax.getX()); - int maxY = Math.max(rotatedMin.getY(), rotatedMax.getY()); - int maxZ = Math.max(rotatedMin.getZ(), rotatedMax.getZ()); - return new PlacedStructurePiece(piece, object, x, y, z, rot, - x + minX, y + minY, z + minZ, x + maxX, y + maxY, z + maxZ); - } - - private boolean withinRadius(PlacedStructurePiece p) { - return p.getMinX() >= originX - radius && p.getMaxX() <= originX + radius - && p.getMinZ() >= originZ - radius && p.getMaxZ() <= originZ + radius; - } - - private boolean collides(List placed, PlacedStructurePiece candidate) { - if (!candidate.getPiece().isCollidable()) { - return false; - } - for (PlacedStructurePiece p : placed) { - if (p.getPiece().isCollidable() && p.intersects(candidate)) { - return true; - } - } - return false; - } - - private int[] rotationCandidates(JigsawJoint joint, RNG rng) { - if (joint == JigsawJoint.ALIGNED) { - return Y_DEGREES; - } - int[] shuffled = {0, 90, 180, 270}; - for (int i = shuffled.length - 1; i > 0; i--) { - int j = rng.i(i + 1); - int t = shuffled[i]; - shuffled[i] = shuffled[j]; - shuffled[j] = t; - } - return shuffled; - } - - private IrisPosition centerOf(IrisObject object) { - return new IrisPosition(object.getW() / 2, object.getH() / 2, object.getD() / 2); - } - - private IrisPosition connectorOffset( - IrisObject object, - IrisJigsawConnector connector, - IrisObjectRotation rotation - ) { - if (structure.resolvedMode() == IrisJigsawMode.PLANAR_JIGSAW) { - IrisPosition dimensions = rotatedDimensions(object, rotation); - IrisPosition position = IrisJigsawConnector.canonicalPlanarPosition( - dimensions, - rotation.rotate(connector.getDirection())); - return new IrisPosition( - position.getX() - dimensions.getX() / 2, - position.getY() - dimensions.getY() / 2, - position.getZ() - dimensions.getZ() / 2); - } - IrisPosition center = centerOf(object); - IrisPosition relative = new IrisPosition( - connector.getPosition().getX() - center.getX(), - connector.getPosition().getY() - center.getY(), - connector.getPosition().getZ() - center.getZ()); - return rotation.rotate(relative, 0, 0, 0); - } - - private IrisPosition logicalCenter(PlacedStructurePiece piece) { - if (structure.resolvedMode() != IrisJigsawMode.PLANAR_JIGSAW) { - return new IrisPosition(piece.getX(), piece.getY(), piece.getZ()); - } - IrisPosition offset = planarPlacementOffset(piece.getObject(), piece.getRotation()); - return new IrisPosition( - piece.getX() - offset.getX(), - piece.getY() - offset.getY(), - piece.getZ() - offset.getZ()); - } - - private IrisPosition rotatedDimensions(IrisObject object, IrisObjectRotation rotation) { - int width = Math.max(1, object.getW()); - int height = Math.max(1, object.getH()); - int depth = Math.max(1, object.getD()); - return quarterTurns(rotation) % 2 == 0 - ? new IrisPosition(width, height, depth) - : new IrisPosition(depth, height, width); - } - - private IrisPosition planarPlacementOffset(IrisObject object, IrisObjectRotation rotation) { - int width = Math.max(1, object.getW()); - int depth = Math.max(1, object.getD()); - return switch (quarterTurns(rotation)) { - case 0 -> new IrisPosition(); - case 1 -> new IrisPosition(0, 0, width % 2 == 0 ? -1 : 0); - case 2 -> new IrisPosition( - width % 2 == 0 ? -1 : 0, - 0, - depth % 2 == 0 ? -1 : 0); - case 3 -> new IrisPosition(depth % 2 == 0 ? -1 : 0, 0, 0); - default -> throw new IllegalStateException("Unsupported planar quarter-turn count"); - }; - } - - private int quarterTurns(IrisObjectRotation rotation) { - return switch (rotation.rotate(IrisDirection.NORTH_NEGATIVE_Z)) { - case NORTH_NEGATIVE_Z -> 0; - case WEST_NEGATIVE_X -> 1; - case SOUTH_POSITIVE_Z -> 2; - case EAST_POSITIVE_X -> 3; - case UP_POSITIVE_Y, DOWN_NEGATIVE_Y -> throw new IllegalStateException( - "Planar jigsaw rotation moved north onto a vertical axis"); - }; - } - - private IrisJigsawPieceEntry weightedPick(List entries, RNG rng) { - long total = 0L; - for (IrisJigsawPieceEntry entry : entries) { - total += entry.getWeight(); - } - if (total <= 0) { - return null; - } - long target = rng.nextLong(total); - for (IrisJigsawPieceEntry entry : entries) { - target -= entry.getWeight(); - if (target < 0) { - return entry; - } - } - return null; - } - - private KList weightedOrder( - IrisJigsawPool pool, - String selectedTheme, - int depth, - Map placementCounts, - boolean allowEmpty, - boolean terminalOnly, - RNG rng - ) { - List eligible = eligibleEntries( - pool, - selectedTheme, - depth, - placementCounts, - allowEmpty, - terminalOnly); - KList remaining = new KList<>(chanceEligibleEntries(eligible, rng)); - KList order = new KList<>(); - while (!remaining.isEmpty()) { - long total = 0L; - for (IrisJigsawPieceEntry e : remaining) { - total += e.getWeight(); - } - long t = rng.nextLong(total); - int idx = 0; - for (int i = 0; i < remaining.size(); i++) { - t -= remaining.get(i).getWeight(); - if (t < 0) { - idx = i; - break; - } - } - order.add(remaining.remove(idx)); - } - return order; - } - - private List eligibleEntries( - IrisJigsawPool pool, - String selectedTheme, - int depth, - Map placementCounts, - boolean allowEmpty, - boolean terminalOnly - ) { - if (pool.getPieces() == null) { - throw assemblyFailure("pool has no piece list"); - } - List eligible = new ArrayList<>(); - List required = new ArrayList<>(); - for (IrisJigsawPieceEntry entry : pool.getPieces()) { - if (entry == null || entry.getWeight() <= 0) { - throw assemblyFailure("pool contains a null or non-positive weighted entry"); - } - if (entry.isEmpty()) { - if (allowEmpty) { - eligible.add(entry); - } - continue; - } - String pieceKey = normalize(entry.getPiece()); - if (pieceKey.isEmpty()) { - throw assemblyFailure("pool contains a weighted entry without a piece key"); - } - IrisJigsawPiece piece = resolver.loadPiece(pieceKey); - if (piece == null) { - throw assemblyFailure("pool references missing piece '" + pieceKey + "'"); - } - int placements = placementCounts.getOrDefault(pieceKey, 0); - if (!pieceEnabled(piece) - || terminalOnly && !piece.resolvedRules().isTerminal() - || !JigsawPoolSelection.pieceEligible(piece, selectedTheme, depth, placements)) { - continue; - } - eligible.add(entry); - if (JigsawPoolSelection.needsMinimumPlacement(piece, placements)) { - required.add(entry); - } - } - return required.isEmpty() ? eligible : required; - } - - private List chanceEligibleEntries( - List entries, - RNG rng - ) { - List eligible = new ArrayList<>(entries.size()); - for (IrisJigsawPieceEntry entry : entries) { - if (JigsawPoolSelection.passesChance(entry, rng)) { - eligible.add(entry); - } - } - return eligible; - } - - private boolean pieceEnabled(IrisJigsawPiece piece) { - return structure.resolvedMode() != IrisJigsawMode.PLANAR_JIGSAW - || PlanarJigsawWorkcellResolver.workcell(planarWorkcells, piece).enabled(); - } - - private void incrementPlacement(Map placementCounts, String pieceKey) { - placementCounts.merge(normalize(pieceKey), 1, Integer::sum); - } - - private String unsatisfiedMinimumPlacement( - Map placementCounts, - String selectedTheme - ) { - for (Map.Entry entry : graph.getPieces().entrySet()) { - IrisJigsawPiece piece = entry.getValue(); - if (!pieceEnabled(piece) || !piece.supportsTheme(selectedTheme)) { - continue; - } - int actual = placementCounts.getOrDefault(entry.getKey(), 0); - int minimum = piece.resolvedRules().getMinimumPlacements(); - if (actual < minimum) { - return "Piece '" + entry.getKey() + "' requires at least " + minimum - + " placement(s) for theme '" + themeLabel(selectedTheme) - + "' but assembled " + actual; - } - } - return ""; - } - - private String themeLabel(String selectedTheme) { - return selectedTheme == null || selectedTheme.isBlank() ? "" : selectedTheme; - } - - private String connectorLocation(OpenConnector connector) { - return connector.wx() + "," + connector.wy() + "," + connector.wz() - + " facing " + connector.facing(); - } - - private String normalize(String value) { - return value == null ? "" : value.trim(); - } - - private void requireConnector(IrisJigsawConnector connector, String pieceKey) { - if (connector == null || connector.getPosition() == null || connector.getDirection() == null - || connector.getTop() == null || connector.getName() == null - || connector.getTargetName() == null || connector.getChannel() == null - || connector.getJoint() == null || connector.getFinalState() == null - || connector.getFinalState().isBlank()) { - throw assemblyFailure("piece '" + pieceKey + "' contains a malformed connector"); - } - } - - private IllegalStateException assemblyFailure(String detail) { - return new IllegalStateException("Structure '" + structure.getLoadKey() + "' assembly failed: " + detail); - } - - private static IllegalStateException invalidGraph(StructureGraphCompilation compilation) { - String structureKey = compilation.getGraph().getStructureKey(); - StringBuilder detail = new StringBuilder(); - for (StructureGraphDiagnostic diagnostic : compilation.getDiagnostics()) { - if (diagnostic.severity() != StructureGraphDiagnostic.Severity.ERROR) { - continue; - } - if (!detail.isEmpty()) { - detail.append("; "); - } - detail.append(diagnostic.message()); - } - return new IllegalStateException("Structure '" + structureKey - + "' assembly rejected its invalid graph: " + detail); - } - - private record OpenConnector(PlacedStructurePiece sourcePiece, IrisJigsawConnector sourceConnector, - int wx, int wy, int wz, IrisDirection facing, IrisDirection top, - String pool, String name, - String targetName, String channel, JigsawJoint joint, int depth, - int pieceDepth, int placementPriority) { - } - - private record PieceExpansion(List connectors, int placementPriority) { - } - - private record ConnectorClosure( - PlacedStructurePiece existingPiece, - IrisJigsawConnector existingConnector, - IrisJigsawConnector candidateConnector - ) { - } - - private record CapReservation(String pieceKey, PlacedStructurePiece piece) { - } - - private enum AttachmentState { - ATTACHED, - CLOSED, - TERMINATED, - NO_MATCH, - FAILED - } - - private record AttachmentResult(AttachmentState state, String detail) { - private AttachmentResult { - Objects.requireNonNull(state); - detail = detail == null ? "" : detail; - } - - private static AttachmentResult success(AttachmentState state) { - if (state == AttachmentState.NO_MATCH || state == AttachmentState.FAILED) { - throw new IllegalArgumentException("A successful attachment requires a resolved state"); - } - return new AttachmentResult(state, ""); - } - - private static AttachmentResult failed(String detail) { - return new AttachmentResult(AttachmentState.FAILED, detail); - } - } - - private record AssemblyOptions(StructureGraphResolver resolver, CompiledStructureGraph graph, - IrisStructure structure, - IrisPosition origin) { - private AssemblyOptions { - Objects.requireNonNull(resolver, "Structure assembly resolver must not be null"); - Objects.requireNonNull(graph, "Compiled structure graph must not be null"); - Objects.requireNonNull(structure, "Structure assembly structure must not be null"); - Objects.requireNonNull(origin, "Structure assembly origin must not be null"); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java b/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java deleted file mode 100644 index 0f73ff88f..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java +++ /dev/null @@ -1,360 +0,0 @@ -package art.arcane.iris.engine.framework; - -import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.builtin.structure.StructureAnchorMode; -import art.arcane.iris.builtin.structure.StructurePlacement; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.matter.MatterCavern; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Objects; -import java.util.function.IntPredicate; - -public final class StructureCaveAnchorResolver { - private static final int CHUNK_COLUMN_COUNT = 256; - private static final int MAX_ATTEMPTS = 64; - private static final int MAX_SCAN_STEP = 16; - private static final int MAX_CLEARANCE = 64; - private static final int MAX_GENERIC_CENTER_SEARCH = 4096; - private static final byte LIQUID_FORCED_AIR = 3; - - private StructureCaveAnchorResolver() { - } - - public static Anchor resolve(Engine engine, StructurePlacement placement, int chunkX, int chunkZ, RNG rng) { - Objects.requireNonNull(engine, "Cave structure anchor requires an engine"); - Objects.requireNonNull(placement, "Cave structure anchor requires a placement"); - Objects.requireNonNull(rng, "Cave structure anchor requires a random source"); - StructureAnchorMode mode = placement.resolvedAnchor(); - if (!mode.isCave() || engine.getMantle() == null || engine.getMantle().getMantle() == null) { - return null; - } - - int worldMin = engine.getMinHeight() + 1; - int worldMax = engine.getMinHeight() + engine.getHeight() - 2; - int minimumY = Math.max(worldMin, Math.min(placement.minHeight(), placement.maxHeight())); - int maximumY = Math.min(worldMax, Math.max(placement.minHeight(), placement.maxHeight())); - if (minimumY > maximumY) { - return null; - } - - int attempts = Math.min(MAX_ATTEMPTS, Math.max(1, placement.caveAnchorAttempts())); - int scanStep = Math.min(MAX_SCAN_STEP, Math.max(1, placement.caveAnchorScanStep())); - int clearance = Math.min(MAX_CLEARANCE, Math.max(1, placement.caveMinimumClearance())); - int chunkMinX = chunkX << 4; - int chunkMinZ = chunkZ << 4; - int[] candidateColumns = candidateColumnIndices(rng, attempts); - for (int candidateColumn : candidateColumns) { - int blockX = chunkMinX + (candidateColumn & 15); - int blockZ = chunkMinZ + (candidateColumn >>> 4); - List anchors = anchorsInColumn( - engine, placement, mode, blockX, blockZ, - minimumY, maximumY, scanStep, clearance); - if (!anchors.isEmpty()) { - return new Anchor(blockX, anchors.get(rng.nextInt(anchors.size())), blockZ); - } - } - return null; - } - - static int[] candidateColumnIndices(RNG rng, int attempts) { - Objects.requireNonNull(rng, "Cave structure column selection requires a random source"); - int count = Math.min(MAX_ATTEMPTS, Math.max(1, attempts)); - int start = rng.nextInt(CHUNK_COLUMN_COUNT); - int stride = (rng.nextInt(CHUNK_COLUMN_COUNT / 2) * 2) + 1; - int[] columns = new int[count]; - for (int index = 0; index < count; index++) { - columns[index] = (start + (index * stride)) & (CHUNK_COLUMN_COUNT - 1); - } - return columns; - } - - static List anchorsInColumn( - Engine engine, - StructurePlacement placement, - StructureAnchorMode mode, - int blockX, - int blockZ, - int minimumY, - int maximumY, - int scanStep, - int clearance - ) { - if (mode == StructureAnchorMode.CAVE_CENTER) { - return centerAnchorsInColumn( - engine, placement, blockX, blockZ, - minimumY, maximumY, scanStep, clearance); - } - List anchors = new ArrayList<>(); - int step = Math.max(1, scanStep); - for (int worldY = minimumY; worldY <= maximumY; worldY += step) { - int mantleY = toMantleY(worldY, engine.getMinHeight()); - if (!matchesGeometry(engine, mode, blockX, mantleY, blockZ, clearance)) { - continue; - } - if (!matchesAnchorFluid(engine, placement, blockX, mantleY, blockZ)) { - continue; - } - if (!matchesBiome(engine, placement, blockX, mantleY, blockZ)) { - continue; - } - anchors.add(worldY); - } - return List.copyOf(anchors); - } - - private static List centerAnchorsInColumn( - Engine engine, - StructurePlacement placement, - int blockX, - int blockZ, - int minimumY, - int maximumY, - int scanStep, - int clearance - ) { - List anchors = new ArrayList<>(); - int step = Math.max(1, scanStep); - int worldOffset = engine.getMinHeight(); - int minimumMantleY = 0; - int maximumMantleY = engine.getHeight() - 1; - int processedThroughWorldY = Integer.MIN_VALUE; - IntPredicate carved = y -> isCarved(engine, blockX, y, blockZ); - for (int worldY = minimumY; worldY <= maximumY; worldY += step) { - if (worldY <= processedThroughWorldY) { - continue; - } - int mantleY = toMantleY(worldY, worldOffset); - if (!carved.test(mantleY)) { - continue; - } - int lower = cavernLowerBound(carved, mantleY, minimumMantleY); - int upper = cavernUpperBound(carved, mantleY, maximumMantleY); - processedThroughWorldY = upper + worldOffset; - if ((long) upper - lower + 1L < Math.max(1, clearance)) { - continue; - } - int lowerCenterWorldY = lower + Math.floorDiv(upper - lower, 2) + worldOffset; - addCenterAnchor( - anchors, engine, placement, blockX, blockZ, - lowerCenterWorldY, minimumY, maximumY); - int upperCenterWorldY = lower + Math.ceilDiv(upper - lower, 2) + worldOffset; - if (upperCenterWorldY != lowerCenterWorldY) { - addCenterAnchor( - anchors, engine, placement, blockX, blockZ, - upperCenterWorldY, minimumY, maximumY); - } - } - return List.copyOf(anchors); - } - - private static void addCenterAnchor( - List anchors, - Engine engine, - StructurePlacement placement, - int blockX, - int blockZ, - int worldY, - int minimumY, - int maximumY - ) { - if (worldY < minimumY || worldY > maximumY) { - return; - } - int mantleY = toMantleY(worldY, engine.getMinHeight()); - if (matchesAnchorFluid(engine, placement, blockX, mantleY, blockZ) - && matchesBiome(engine, placement, blockX, mantleY, blockZ)) { - anchors.add(worldY); - } - } - - static boolean matchesGeometry( - Engine engine, - StructureAnchorMode mode, - int blockX, - int mantleY, - int blockZ, - int clearance - ) { - IntPredicate carved = y -> isCarved(engine, blockX, y, blockZ); - if (mode == StructureAnchorMode.CAVE_CENTER) { - return matchesCenterGeometry( - carved, mantleY, Math.max(1, clearance), 0, engine.getHeight() - 1); - } - return matchesGeometry(carved, mode, mantleY, clearance); - } - - static boolean matchesGeometry( - IntPredicate carved, - StructureAnchorMode mode, - int mantleY, - int clearance - ) { - if (!carved.test(mantleY)) { - return false; - } - int required = Math.max(1, clearance); - return switch (mode) { - case CAVE_FLOOR -> !carved.test(mantleY - 1) - && carvedRun(carved, mantleY, 1, required); - case CAVE_CEILING -> !carved.test(mantleY + 1) - && carvedRun(carved, mantleY, -1, required); - case CAVE_CENTER -> matchesCenterGeometry( - carved, mantleY, required, - saturatedSubtract(mantleY, MAX_GENERIC_CENTER_SEARCH), - saturatedAdd(mantleY, MAX_GENERIC_CENTER_SEARCH)); - case CAVE_ANY -> carvedRun( - carved, mantleY - Math.floorDiv(required - 1, 2), 1, required); - default -> false; - }; - } - - private static boolean matchesCenterGeometry( - IntPredicate carved, - int mantleY, - int clearance, - int minimumY, - int maximumY - ) { - if (!carved.test(mantleY)) { - return false; - } - int lower = cavernLowerBound(carved, mantleY, minimumY); - int upper = cavernUpperBound(carved, mantleY, maximumY); - if ((long) upper - lower + 1L < clearance) { - return false; - } - int lowerCenter = lower + Math.floorDiv(upper - lower, 2); - int upperCenter = lower + Math.ceilDiv(upper - lower, 2); - return mantleY == lowerCenter || mantleY == upperCenter; - } - - private static int cavernLowerBound(IntPredicate carved, int mantleY, int minimumY) { - int lower = mantleY; - while (lower > minimumY && carved.test(lower - 1)) { - lower--; - } - return lower; - } - - private static int cavernUpperBound(IntPredicate carved, int mantleY, int maximumY) { - int upper = mantleY; - while (upper < maximumY && carved.test(upper + 1)) { - upper++; - } - return upper; - } - - private static int saturatedSubtract(int value, int amount) { - long result = (long) value - amount; - return result < Integer.MIN_VALUE ? Integer.MIN_VALUE : (int) result; - } - - private static int saturatedAdd(int value, int amount) { - long result = (long) value + amount; - return result > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) result; - } - - private static boolean carvedRun( - IntPredicate carved, - int mantleY, - int direction, - int length - ) { - for (int offset = 0; offset < length; offset++) { - if (!carved.test(mantleY + (direction * offset))) { - return false; - } - } - return true; - } - - private static boolean isCarved(Engine engine, int blockX, int mantleY, int blockZ) { - if (mantleY < 0 || mantleY >= engine.getHeight()) { - return false; - } - MatterCavern cavern = cavernAt(engine, blockX, mantleY, blockZ); - return cavern != null && cavern.isCavern(); - } - - private static boolean matchesAnchorFluid( - Engine engine, - StructurePlacement placement, - int blockX, - int mantleY, - int blockZ - ) { - MatterCavern cavern = cavernAt(engine, blockX, mantleY, blockZ); - return acceptsAnchorFluid( - placement.underwater(), - cavern, - mantleY, - engine.getDimension().getModuleSettings().find(CaveLavaHeightSettings.class).map(CaveLavaHeightSettings::height).orElse(CaveLavaHeightSettings.DEFAULT_HEIGHT)); - } - - static boolean acceptsAnchorFluid( - boolean underwater, - MatterCavern cavern, - int mantleY, - int defaultLavaHeight - ) { - if (cavern == null || !cavern.isCavern()) { - return false; - } - if (underwater) { - return true; - } - if (cavern.getLiquid() == LIQUID_FORCED_AIR) { - return true; - } - return cavern.isAir() && mantleY > defaultLavaHeight; - } - - private static MatterCavern cavernAt(Engine engine, int blockX, int mantleY, int blockZ) { - return engine.getMantle().getMantle().get(blockX, mantleY, blockZ, MatterCavern.class); - } - - static int toMantleY(int worldY, int worldMinHeight) { - return Math.subtractExact(worldY, worldMinHeight); - } - - private static boolean matchesBiome( - Engine engine, - StructurePlacement placement, - int blockX, - int mantleY, - int blockZ - ) { - if (placement.caveBiomes().isEmpty()) { - return true; - } - IrisBiome biome = engine.getCaveOrMantleBiome(blockX, mantleY, blockZ); - if (biome == null || biome.getLoadKey() == null) { - return false; - } - String actual = biome.getLoadKey().toLowerCase(Locale.ROOT); - for (String allowed : placement.caveBiomes()) { - if (matchesBiomeKey(actual, allowed)) { - return true; - } - } - return false; - } - - static boolean matchesBiomeKey(String actual, String allowed) { - if (actual == null || actual.isBlank() || allowed == null || allowed.isBlank()) { - return false; - } - String normalizedActual = actual.trim().toLowerCase(Locale.ROOT); - String normalizedAllowed = allowed.trim().toLowerCase(Locale.ROOT); - return normalizedActual.equals(normalizedAllowed) - || normalizedActual.endsWith(":" + normalizedAllowed) - || normalizedAllowed.endsWith(":" + normalizedActual); - } - - public record Anchor(int x, int y, int z) { - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java b/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java deleted file mode 100644 index bc99627de..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java +++ /dev/null @@ -1,115 +0,0 @@ -package art.arcane.iris.engine.framework; - -import art.arcane.iris.builtin.structure.StructurePlacement; -import art.arcane.iris.builtin.structure.StructurePlacementSettings; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.volmlib.util.collection.KList; - -import java.util.Collections; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * The structure placements that apply at a chunk: its biome's, its cave biome's cave-anchored ones, its region's and - * the dimension's. Each world keeps which of those levels declare placements at all, so chunks skip the biome and - * region lookups a pack never needs. - */ -public final class StructurePlacementScope { - private StructurePlacementScope() { - } - - /** The placements {@code owner} declares in its {@code "structures"} settings; empty for none. */ - public static List placementsOf(IrisRegistrant owner) { - if (owner == null) { - return List.of(); - } - return owner.getModuleSettings().find(StructurePlacementSettings.class) - .map(StructurePlacementSettings::placements) - .orElse(List.of()); - } - - public static KList placementsAt(Engine engine, int chunkX, int chunkZ) { - Engine activeEngine = Objects.requireNonNull(engine, "Structure placement scope requires an engine"); - IrisComplex complex = activeEngine.getComplex(); - int blockX = (chunkX << 4) + 8; - int blockZ = (chunkZ << 4) + 8; - KList placements = new KList<>(); - Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); - ScopeIndex index = scopeIndex(activeEngine); - if (complex != null) { - if (index.biome()) { - IrisBiome biome = complex.getTrueBiomeStream().get(blockX, blockZ); - addUnique(placements, seen, placementsOf(biome)); - } - if (index.caveBiome()) { - IrisBiome caveBiome = complex.getCaveBiomeStream().get(blockX, blockZ); - addCaveUnique(placements, seen, placementsOf(caveBiome)); - } - if (index.region()) { - IrisRegion region = complex.getRegionStream().get(blockX, blockZ); - addUnique(placements, seen, placementsOf(region)); - } - } - if (index.dimension()) { - addUnique(placements, seen, placementsOf(activeEngine.getDimension())); - } - return placements; - } - - private static ScopeIndex scopeIndex(Engine engine) { - return engine.getGeneration().state(ScopeIndex.class, StructurePlacementScope::buildScopeIndex); - } - - private static ScopeIndex buildScopeIndex(Engine engine) { - boolean biome = false; - boolean caveBiome = false; - KList allBiomes = engine.getAllBiomes(); - if (allBiomes == null) { - biome = true; - caveBiome = true; - } else { - for (IrisBiome candidate : allBiomes) { - List structures = placementsOf(candidate); - if (structures.isEmpty()) { - continue; - } - biome = true; - caveBiome |= structures.stream().anyMatch(placement -> placement.resolvedAnchor().isCave()); - } - } - boolean region = false; - if (engine.getDimension() != null) { - KList allRegions = engine.getDimension().getAllRegions(engine); - region = allRegions == null - || allRegions.stream().anyMatch(candidate -> !placementsOf(candidate).isEmpty()); - } - boolean dimension = !placementsOf(engine.getDimension()).isEmpty(); - return new ScopeIndex(biome, caveBiome, region, dimension); - } - - private static void addUnique(KList destination, Set seen, - List source) { - for (StructurePlacement placement : source) { - if (placement != null && seen.add(placement)) { - destination.add(placement); - } - } - } - - private static void addCaveUnique(KList destination, Set seen, - List source) { - for (StructurePlacement placement : source) { - if (placement != null && placement.resolvedAnchor().isCave() && seen.add(placement)) { - destination.add(placement); - } - } - } - - private record ScopeIndex(boolean biome, boolean caveBiome, boolean region, boolean dimension) { - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/CompiledStructureGraph.java b/src/main/java/art/arcane/iris/engine/framework/structure/CompiledStructureGraph.java deleted file mode 100644 index ec18f15a6..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/CompiledStructureGraph.java +++ /dev/null @@ -1,101 +0,0 @@ -package art.arcane.iris.engine.framework.structure; - -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.structure.IrisStructure; - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -public final class CompiledStructureGraph { - private final IrisStructure structure; - private final Map pools; - private final Map pieces; - private final Map objects; - private final Set reachablePools; - private final Set reachablePieces; - - private CompiledStructureGraph(Builder builder) { - structure = builder.structure; - pools = Collections.unmodifiableMap(new LinkedHashMap<>(builder.pools)); - pieces = Collections.unmodifiableMap(new LinkedHashMap<>(builder.pieces)); - objects = Collections.unmodifiableMap(new LinkedHashMap<>(builder.objects)); - reachablePools = Collections.unmodifiableSet(new LinkedHashSet<>(builder.reachablePools)); - reachablePieces = Collections.unmodifiableSet(new LinkedHashSet<>(builder.reachablePieces)); - } - - static Builder builder(IrisStructure structure) { - return new Builder(structure); - } - - public IrisStructure getStructure() { - return structure; - } - - public String getStructureKey() { - String key = structure.getLoadKey(); - return key == null || key.isBlank() ? "" : key; - } - - public Map getPools() { - return pools; - } - - public Map getPieces() { - return pieces; - } - - public Map getObjects() { - return objects; - } - - public Set getReachablePools() { - return reachablePools; - } - - public Set getReachablePieces() { - return reachablePieces; - } - - static final class Builder { - private final IrisStructure structure; - private final Map pools = new LinkedHashMap<>(); - private final Map pieces = new LinkedHashMap<>(); - private final Map objects = new LinkedHashMap<>(); - private final Set reachablePools = new LinkedHashSet<>(); - private final Set reachablePieces = new LinkedHashSet<>(); - - private Builder(IrisStructure structure) { - this.structure = Objects.requireNonNull(structure); - } - - Map pools() { - return pools; - } - - Map pieces() { - return pieces; - } - - Map objects() { - return objects; - } - - Set reachablePools() { - return reachablePools; - } - - Set reachablePieces() { - return reachablePieces; - } - - CompiledStructureGraph build() { - return new CompiledStructureGraph(this); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/IrisObjectFrameReader.java b/src/main/java/art/arcane/iris/engine/framework/structure/IrisObjectFrameReader.java deleted file mode 100644 index 38292bd5b..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/IrisObjectFrameReader.java +++ /dev/null @@ -1,386 +0,0 @@ -package art.arcane.iris.engine.framework.structure; - -import art.arcane.iris.engine.object.prefab.IrisObject; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; - -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.LinkedHashSet; -import java.util.Objects; -import java.util.Set; - -public final class IrisObjectFrameReader { - private static final String HEADER = "Iris V2 IOB;"; - private static final int MAX_FILE_BYTES = 64 * 1024 * 1024; - private static final int MAX_TILE_COUNT = 65_536; - private static final int MAX_CANDIDATE_OFFSETS = 1_024; - private static final long MAX_TILE_PARSE_STATES = 262_144L; - private static final int MAX_LEGACY_SIGN_COLOR_INDEX = 15; - - private IrisObjectFrameReader() { - } - - public static IrisObject readBounds(InputStream stream, String resourceName) throws IOException { - String activeResourceName = resourceName == null || resourceName.isBlank() - ? "" : resourceName; - try { - byte[] content = readLimitedContent(Objects.requireNonNull(stream), activeResourceName); - return readBounds(content, activeResourceName); - } catch (IOException e) { - if (e.getMessage() != null && e.getMessage().startsWith("Malformed Iris object resource ")) { - throw e; - } - throw malformed(activeResourceName, e.getMessage() == null - ? e.getClass().getSimpleName() : e.getMessage()); - } catch (RuntimeException e) { - throw malformed(activeResourceName, e.getMessage() == null - ? e.getClass().getSimpleName() : e.getMessage()); - } - } - - private static IrisObject readBounds(byte[] content, String resourceName) throws IOException { - ByteArrayInputStream bytes = new ByteArrayInputStream(content); - DataInputStream input = new DataInputStream(bytes); - int width = input.readInt(); - int height = input.readInt(); - int depth = input.readInt(); - long volume = requireDimensions(resourceName, width, height, depth); - if (!HEADER.equals(input.readUTF())) { - throw malformed(resourceName, "invalid header"); - } - - int paletteSize = input.readShort(); - if (paletteSize < 0) { - throw malformed(resourceName, "palette exceeds the signed IOB limit"); - } - for (int index = 0; index < paletteSize; index++) { - if (input.readUTF().isBlank()) { - throw malformed(resourceName, "palette entry " + index + " is blank"); - } - } - - int blockCount = input.readInt(); - if (blockCount < 0 || blockCount > volume || blockCount > 0 && paletteSize == 0) { - throw malformed(resourceName, "invalid block count " + blockCount); - } - for (int index = 0; index < blockCount; index++) { - int x = input.readShort(); - int y = input.readShort(); - int z = input.readShort(); - int paletteIndex = input.readShort(); - requirePosition(resourceName, "block", index, x, y, z, width, height, depth); - if (paletteIndex < 0 || paletteIndex >= paletteSize) { - throw malformed(resourceName, "block " + index - + " references invalid palette index " + paletteIndex); - } - } - - int tileCount = input.readInt(); - if (tileCount < 0 || tileCount > volume) { - throw malformed(resourceName, "invalid tile count " + tileCount); - } - if (tileCount > MAX_TILE_COUNT) { - throw malformed(resourceName, "tile count " + tileCount - + " exceeds limit " + MAX_TILE_COUNT); - } - int tileStart = content.length - bytes.available(); - requireCompleteTileFraming(content, tileStart, tileCount, width, height, depth, resourceName); - return new IrisObject(width, height, depth); - } - - private static void requireCompleteTileFraming( - byte[] content, - int tileStart, - int tileCount, - int width, - int height, - int depth, - String resourceName - ) throws IOException { - Set offsets = Set.of(tileStart); - long parseStates = 0L; - for (int tileIndex = 0; tileIndex < tileCount; tileIndex++) { - Set nextOffsets = new LinkedHashSet<>(); - TileFailureTracker failures = new TileFailureTracker(); - for (int offset : offsets) { - parseStates++; - requireParseStateBudget(resourceName, tileIndex, parseStates); - TilePrefix prefix = readTilePrefix( - content, offset, width, height, depth, tileIndex, failures); - if (prefix == null) { - continue; - } - int modernEnd = readModernTileEnd( - content, prefix.payloadOffset(), tileIndex, failures); - if (modernEnd >= 0) { - addCandidateOffset(resourceName, tileIndex, nextOffsets, modernEnd); - } - for (int legacyEnd : readLegacyTileEnds( - content, prefix.payloadOffset(), tileIndex, failures)) { - addCandidateOffset(resourceName, tileIndex, nextOffsets, legacyEnd); - } - } - if (nextOffsets.isEmpty()) { - throw malformed(resourceName, failures.detailOr( - "tile " + tileIndex + " is truncated or malformed")); - } - offsets = nextOffsets; - } - if (!offsets.contains(content.length)) { - throw malformed(resourceName, "tile records leave trailing or incomplete data"); - } - } - - private static TilePrefix readTilePrefix( - byte[] content, - int offset, - int width, - int height, - int depth, - int tileIndex, - TileFailureTracker failures - ) { - try { - ByteArrayInputStream bytes = slice(content, offset); - DataInputStream input = new DataInputStream(bytes); - int x = input.readShort(); - int y = input.readShort(); - int z = input.readShort(); - if (!withinSignedObjectAxis(x, width) || !withinSignedObjectAxis(y, height) - || !withinSignedObjectAxis(z, depth)) { - failures.record("tile " + tileIndex + " position " + x + "," + y + "," + z - + " is outside object bounds", 20); - return null; - } - return new TilePrefix(content.length - bytes.available()); - } catch (IOException | RuntimeException e) { - return null; - } - } - - private static int readModernTileEnd( - byte[] content, - int offset, - int tileIndex, - TileFailureTracker failures - ) { - try { - ByteArrayInputStream bytes = slice(content, offset); - DataInputStream input = new DataInputStream(bytes); - String material = input.readUTF(); - if (material.isBlank()) { - failures.record("tile " + tileIndex + " modern material is blank", 40); - return -1; - } - JsonElement properties = JsonParser.parseString(input.readUTF()); - if (!properties.isJsonObject()) { - failures.record("tile " + tileIndex - + " modern properties are not a JSON object", 30); - return -1; - } - return content.length - bytes.available(); - } catch (IOException | RuntimeException e) { - return -1; - } - } - - private static Set readLegacyTileEnds( - byte[] content, - int offset, - int tileIndex, - TileFailureTracker failures - ) { - try { - ByteArrayInputStream bytes = slice(content, offset); - DataInputStream input = new DataInputStream(bytes); - int id = input.readShort(); - return switch (id) { - case 0 -> singletonEnd(content, readLegacySign(input, bytes, tileIndex, failures)); - case 1 -> readLegacySpawnerEnds(content, content.length - bytes.available()); - case 2 -> readLegacyBannerEnds(content, input, bytes); - case 3 -> singletonEnd(content, readLegacyLootable(input, bytes)); - default -> Set.of(); - }; - } catch (IOException | RuntimeException e) { - return Set.of(); - } - } - - private static int readLegacySign( - DataInputStream input, - ByteArrayInputStream bytes, - int tileIndex, - TileFailureTracker failures - ) throws IOException { - input.readUTF(); - input.readUTF(); - input.readUTF(); - input.readUTF(); - int colorIndex = input.readByte(); - if (colorIndex < 0 || colorIndex > MAX_LEGACY_SIGN_COLOR_INDEX) { - failures.record("tile " + tileIndex + " legacy sign color index " + colorIndex - + " is outside 0.." + MAX_LEGACY_SIGN_COLOR_INDEX, 50); - throw new IOException("Invalid legacy sign color index"); - } - return bytes.available(); - } - - private static Set readLegacySpawnerEnds(byte[] content, int payloadOffset) { - Set ends = new LinkedHashSet<>(); - try { - ByteArrayInputStream keyedBytes = slice(content, payloadOffset); - new DataInputStream(keyedBytes).readUTF(); - ends.add(content.length - keyedBytes.available()); - } catch (IOException | RuntimeException ignored) { - } - if (payloadOffset <= content.length - Short.BYTES) { - ends.add(payloadOffset + Short.BYTES); - } - return Set.copyOf(ends); - } - - private static Set readLegacyBannerEnds( - byte[] content, - DataInputStream input, - ByteArrayInputStream bytes - ) throws IOException { - input.readUnsignedByte(); - int patternCount = input.readUnsignedByte(); - int patternsOffset = content.length - bytes.available(); - Set ends = new LinkedHashSet<>(); - try { - ByteArrayInputStream keyedBytes = slice(content, patternsOffset); - DataInputStream keyedInput = new DataInputStream(keyedBytes); - for (int index = 0; index < patternCount; index++) { - keyedInput.readUnsignedByte(); - keyedInput.readUTF(); - } - ends.add(content.length - keyedBytes.available()); - } catch (IOException | RuntimeException ignored) { - } - long legacyEnd = (long) patternsOffset + (long) patternCount * 2L; - if (legacyEnd <= content.length) { - ends.add((int) legacyEnd); - } - return Set.copyOf(ends); - } - - private static int readLegacyLootable(DataInputStream input, ByteArrayInputStream bytes) throws IOException { - input.readUTF(); - input.readUTF(); - input.readLong(); - return bytes.available(); - } - - private static Set singletonEnd(byte[] content, int remaining) { - return Set.of(content.length - remaining); - } - - private static byte[] readLimitedContent(InputStream stream, String resourceName) throws IOException { - return readLimitedContent(stream, resourceName, MAX_FILE_BYTES); - } - - static byte[] readLimitedContent( - InputStream stream, - String resourceName, - int maximumBytes - ) throws IOException { - byte[] content = stream.readNBytes(maximumBytes + 1); - if (content.length > maximumBytes) { - throw malformed(resourceName, "file exceeds " + maximumBytes + "-byte limit"); - } - return content; - } - - private static void addCandidateOffset( - String resourceName, - int tileIndex, - Set offsets, - int offset - ) throws IOException { - offsets.add(offset); - if (offsets.size() > MAX_CANDIDATE_OFFSETS) { - throw malformed(resourceName, "tile " + tileIndex + " exceeds candidate-offset limit " - + MAX_CANDIDATE_OFFSETS); - } - } - - private static void requireParseStateBudget( - String resourceName, - int tileIndex, - long parseStates - ) throws IOException { - if (parseStates > MAX_TILE_PARSE_STATES) { - throw malformed(resourceName, "tile " + tileIndex + " exceeds parse-state limit " - + MAX_TILE_PARSE_STATES); - } - } - - private static ByteArrayInputStream slice(byte[] content, int offset) { - if (offset < 0 || offset > content.length) { - throw new IllegalArgumentException("Invalid IOB frame offset " + offset); - } - return new ByteArrayInputStream(content, offset, content.length - offset); - } - - private static long requireDimensions(String resourceName, int width, int height, int depth) throws IOException { - if (width < 1 || height < 1 || depth < 1) { - throw malformed(resourceName, "invalid dimensions " + width + "x" + height + "x" + depth); - } - try { - return Math.multiplyExact(Math.multiplyExact((long) width, height), depth); - } catch (ArithmeticException e) { - throw malformed(resourceName, "dimensions overflow the IOB volume limit"); - } - } - - private static void requirePosition( - String resourceName, - String type, - int index, - int x, - int y, - int z, - int width, - int height, - int depth - ) throws IOException { - if (!withinSignedObjectAxis(x, width) || !withinSignedObjectAxis(y, height) - || !withinSignedObjectAxis(z, depth)) { - throw malformed(resourceName, type + " " + index + " position " - + x + "," + y + "," + z + " is outside object bounds"); - } - } - - private static boolean withinSignedObjectAxis(int coordinate, int size) { - int center = size / 2; - return coordinate >= -center && coordinate < size - center; - } - - private static IOException malformed(String resourceName, String detail) { - return new IOException("Malformed Iris object resource " + resourceName + ": " + detail); - } - - private record TilePrefix(int payloadOffset) { - } - - private static final class TileFailureTracker { - private String detail; - private int priority = Integer.MIN_VALUE; - - private void record(String candidateDetail, int candidatePriority) { - if (candidatePriority <= priority) { - return; - } - detail = candidateDetail; - priority = candidatePriority; - } - - private String detailOr(String fallback) { - return detail == null ? fallback : detail; - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/JigsawPoolSelection.java b/src/main/java/art/arcane/iris/engine/framework/structure/JigsawPoolSelection.java deleted file mode 100644 index 8e18400e4..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/JigsawPoolSelection.java +++ /dev/null @@ -1,104 +0,0 @@ -package art.arcane.iris.engine.framework.structure; - -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceRules; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet; -import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.volmlib.util.math.RNG; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -public final class JigsawPoolSelection { - private JigsawPoolSelection() { - } - - public static String directFallbackKey(IrisJigsawPool pool) { - Objects.requireNonNull(pool); - return normalize(pool.getFallback()); - } - - public static List candidatePoolKeys( - String primaryKey, - IrisJigsawPool primaryPool, - boolean includePrimary - ) { - Objects.requireNonNull(primaryPool); - String normalizedPrimary = normalize(primaryKey); - String directFallback = directFallbackKey(primaryPool); - if (!includePrimary) { - return directFallback.isEmpty() ? List.of() : List.of(directFallback); - } - if (normalizedPrimary.isEmpty()) { - return List.of(); - } - return directFallback.isEmpty() - ? List.of(normalizedPrimary) - : List.of(normalizedPrimary, directFallback); - } - - public static String selectTheme(IrisStructure structure, RNG rng) { - IrisStructure activeStructure = Objects.requireNonNull(structure); - RNG activeRng = Objects.requireNonNull(rng); - if (activeStructure.getThemeSets() == null || activeStructure.getThemeSets().isEmpty()) { - return ""; - } - List themes = new ArrayList<>(activeStructure.getThemeSets().size()); - long totalWeight = 0L; - for (IrisJigsawThemeSet theme : activeStructure.getThemeSets()) { - if (theme == null || normalize(theme.getKey()).isEmpty() || theme.getWeight() <= 0) { - throw new IllegalArgumentException("Jigsaw theme sets require non-blank keys and positive weights"); - } - themes.add(theme); - totalWeight = Math.addExact(totalWeight, theme.getWeight()); - } - if (themes.size() == 1) { - return normalize(themes.getFirst().getKey()); - } - long target = activeRng.nextLong(totalWeight); - for (IrisJigsawThemeSet theme : themes) { - target -= theme.getWeight(); - if (target < 0L) { - return normalize(theme.getKey()); - } - } - return normalize(themes.getLast().getKey()); - } - - public static boolean passesChance(IrisJigsawPieceEntry entry, RNG rng) { - IrisJigsawPieceEntry activeEntry = Objects.requireNonNull(entry); - RNG activeRng = Objects.requireNonNull(rng); - double chance = activeEntry.getChance(); - if (!Double.isFinite(chance) || chance < 0D || chance > 1D) { - throw new IllegalArgumentException("Jigsaw pool membership chance must be finite and within 0 and 1"); - } - if (!activeEntry.requiresChanceRoll()) { - return chance >= 1D; - } - return activeEntry.passesChance(activeRng.nextDouble()); - } - - public static boolean pieceEligible( - IrisJigsawPiece piece, - String selectedTheme, - int depth, - int existingPlacements - ) { - IrisJigsawPiece activePiece = Objects.requireNonNull(piece); - IrisJigsawPieceRules rules = activePiece.resolvedRules(); - return activePiece.supportsTheme(normalize(selectedTheme)) - && rules.allowsDepth(depth) - && rules.allowsPlacement(existingPlacements); - } - - public static boolean needsMinimumPlacement(IrisJigsawPiece piece, int existingPlacements) { - return Objects.requireNonNull(piece).resolvedRules().requiresMorePlacements(existingPlacements); - } - - private static String normalize(String value) { - return value == null ? "" : value.trim(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java b/src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java deleted file mode 100644 index befa246d1..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java +++ /dev/null @@ -1,392 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.framework.structure; - -import art.arcane.iris.builtin.anchor.PlaceTrait; -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.core.pack.PackValidationIo; -import art.arcane.volmlib.util.json.JSONArray; -import art.arcane.volmlib.util.json.JSONObject; -import com.volmit.validation.Problem; -import com.volmit.validation.Subject; - -import java.io.File; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - -/** - * Checks the structure placements of a pack's dimensions, regions and biomes that replace a vanilla structure with - * an Iris one ({@code nativeSuppression: REPLACE_SOURCE}): only a dimension may, it must name Iris structures, each - * with a namespaced {@code vanillaSource}, that {@link StructureGraphValidation} found always produce output, and - * whose sampled pieces fit the placement's height band inside the dimension. Reads the pack's JSON as written, so a - * value of the wrong type is reported rather than read as a default. Every problem is an error about the file of the - * dimension, region or biome. It runs with the structure graph check, whose samples it needs. - */ -public final class NativeReplacementValidation { - private static final List STRUCTURE_HOST_FOLDERS = List.of("dimensions", "regions", "biomes"); - private static final String DIMENSIONS_FOLDER = "dimensions"; - private static final String JSON_EXTENSION = ".json"; - private static final Pattern RESOURCE_KEY_PATTERN = Pattern.compile("[a-z0-9_.-]+:[a-z0-9/._-]+"); - - private NativeReplacementValidation() { - } - - /** - * Checks the pack in {@code packFolder}. - * - * @param replacementOutputStructures the structures that always produce output, which alone may replace a vanilla one - * @param sampledVerticalEnvelopes each viable structure's sampled envelopes - */ - public static List validate( - File packFolder, - Set replacementOutputStructures, - Map> sampledVerticalEnvelopes - ) { - List problems = new ArrayList<>(); - if (packFolder == null || !packFolder.isDirectory()) { - return problems; - } - Set viableStructures = replacementOutputStructures == null - ? Set.of() : replacementOutputStructures; - Map> verticalEnvelopes = - sampledVerticalEnvelopes == null ? Map.of() : sampledVerticalEnvelopes; - Map structures = readStructures(packFolder); - for (String folderName : STRUCTURE_HOST_FOLDERS) { - File resourceFolder = new File(packFolder, folderName); - if (!resourceFolder.isDirectory()) { - continue; - } - List resourceFiles = PackValidationIo.listJsonRecursive(resourceFolder); - resourceFiles.sort(Comparator.comparing(File::getPath)); - for (File resourceFile : resourceFiles) { - JSONObject resource = PackValidationIo.readJson(resourceFile); - if (resource == null) { - continue; - } - String resourceKey = PackValidationIo.deriveKey(resourceFolder, resourceFile); - Subject file = Subject.file(folderName + "/" + resourceKey + JSON_EXTENSION); - for (String error : validateResource(folderName, resourceKey, resource, structures, viableStructures, verticalEnvelopes)) { - problems.add(Problem.error(file, error)); - } - } - } - return problems; - } - - private static Map readStructures(File packFolder) { - File structuresFolder = new File(packFolder, StructureResources.STRUCTURES.folder()); - Map structures = new HashMap<>(); - for (File structureFile : PackValidationIo.listJsonRecursive(structuresFolder)) { - JSONObject structure = PackValidationIo.readJson(structureFile); - if (structure != null) { - structures.put(PackValidationIo.deriveKey(structuresFolder, structureFile), structure); - } - } - return structures; - } - - private static List validateResource( - String folderName, - String resourceKey, - JSONObject resource, - Map structures, - Set viableStructures, - Map> verticalEnvelopes - ) { - List blockingErrors = new ArrayList<>(); - JSONArray placements = resource.optJSONArray("structures"); - if (placements == null) { - return blockingErrors; - } - String resourceType = structureHostType(folderName); - for (int placementIndex = 0; placementIndex < placements.length(); placementIndex++) { - JSONObject placement = placements.optJSONObject(placementIndex); - if (placement == null || !placement.has("nativeSuppression")) { - continue; - } - Object rawSuppression = placement.opt("nativeSuppression"); - if (!(rawSuppression instanceof String suppression)) { - blockingErrors.add(resourceType + " '" + resourceKey + "' structures[" - + placementIndex + "].nativeSuppression must be NONE or REPLACE_SOURCE."); - continue; - } - if ("NONE".equals(suppression)) { - continue; - } - if (!"REPLACE_SOURCE".equals(suppression)) { - blockingErrors.add(resourceType + " '" + resourceKey + "' structures[" - + placementIndex + "].nativeSuppression has unsupported value '" - + suppression + "'. Use NONE or REPLACE_SOURCE."); - continue; - } - if (!DIMENSIONS_FOLDER.equals(folderName)) { - blockingErrors.add(resourceType + " '" + resourceKey + "' structures[" - + placementIndex + "] requests REPLACE_SOURCE, but native replacement is only" - + " valid on dimension-level placements."); - continue; - } - JSONArray references = placement.optJSONArray("structures"); - JSONArray nativeStructures = placement.optJSONArray("nativeStructures"); - if (nativeStructures != null && nativeStructures.length() > 0) { - continue; - } - if (references == null || references.length() == 0) { - blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex - + "] requests REPLACE_SOURCE without any structure backend."); - continue; - } - for (int referenceIndex = 0; referenceIndex < references.length(); referenceIndex++) { - Object rawReference = references.opt(referenceIndex); - if (!(rawReference instanceof String structureKey) || structureKey.isBlank()) { - blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex - + "].structures[" + referenceIndex - + "] must name an Iris structure for REPLACE_SOURCE."); - continue; - } - JSONObject structure = structures.get(structureKey); - if (structure == null) { - blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex - + "] cannot REPLACE_SOURCE with missing or invalid structure '" - + structureKey + "'."); - continue; - } - String vanillaSource = structure.optString("vanillaSource", "").trim(); - if (!RESOURCE_KEY_PATTERN.matcher(vanillaSource).matches()) { - blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex - + "] requests REPLACE_SOURCE for structure '" + structureKey - + "', but its vanillaSource is not a valid namespaced registry key."); - } - if (!viableStructures.contains(structureKey)) { - blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex - + "] requests REPLACE_SOURCE for structure '" + structureKey - + "', but that structure is not runtime-viable. Native generation will not" - + " be used as a fallback."); - continue; - } - validateReplacementVerticalEnvelope( - resourceKey, - resource, - placementIndex, - placement, - structureKey, - structure, - verticalEnvelopes.get(structureKey), - blockingErrors); - } - } - return blockingErrors; - } - - private static String structureHostType(String folderName) { - return switch (folderName) { - case "dimensions" -> "Dimension"; - case "regions" -> "Region"; - case "biomes" -> "Biome"; - default -> "Resource"; - }; - } - - private static void validateReplacementVerticalEnvelope( - String dimensionKey, - JSONObject dimension, - int placementIndex, - JSONObject placement, - String structureKey, - JSONObject structure, - List sampledVerticalEnvelopes, - List blockingErrors - ) { - String context = "Dimension '" + dimensionKey + "' structures[" + placementIndex - + "] REPLACE_SOURCE structure '" + structureKey + "'"; - if (sampledVerticalEnvelopes == null || sampledVerticalEnvelopes.isEmpty()) { - blockingErrors.add(context + " has no sampled vertical envelope. Native generation will not" - + " be used as a fallback."); - return; - } - - DimensionVerticalBounds worldBounds = resolveDimensionVerticalBounds(dimension, context, blockingErrors); - PlacementVerticalBounds placementBounds = resolvePlacementVerticalBounds(placement, context, blockingErrors); - ObjectPlaceMode placeMode = resolvePlaceMode(structure, context, blockingErrors); - if (worldBounds == null || placementBounds == null || placeMode == null) { - return; - } - - for (StructureGraphValidation.SampledVerticalEnvelope sampled : sampledVerticalEnvelopes) { - boolean exactY = placementBounds.underground() - || sampled.pieceCount() > 1 - || placeMode.placeMode().has(PlaceTrait.FREE_HEIGHT); - if (!exactY) { - continue; - } - - long minimumYOffset = sampled.minimumYOffset(); - long maximumYOffset = sampled.maximumYOffset(); - boolean surfaceAligned = !placementBounds.underground() - && sampled.pieceCount() > 1 - && !placeMode.placeMode().has(PlaceTrait.FREE_HEIGHT); - if (surfaceAligned) { - maximumYOffset -= minimumYOffset; - minimumYOffset = 0L; - } - - boolean fitsConfiguredRange; - if (placementBounds.underground()) { - long minimumAnchor = Math.max( - Math.max(placementBounds.minimumY(), worldBounds.minimumY()), - worldBounds.minimumY() - minimumYOffset); - long maximumAnchor = Math.min( - Math.min(placementBounds.maximumY(), worldBounds.maximumY()), - worldBounds.maximumY() - maximumYOffset); - fitsConfiguredRange = minimumAnchor <= maximumAnchor; - } else { - long minimumTerrainY = Math.max(placementBounds.minimumY(), worldBounds.minimumY()); - long maximumTerrainY = Math.min(placementBounds.maximumY(), worldBounds.maximumY()); - fitsConfiguredRange = minimumTerrainY <= maximumTerrainY - && minimumTerrainY + minimumYOffset >= worldBounds.minimumY() - && maximumTerrainY + maximumYOffset <= worldBounds.maximumY(); - } - if (fitsConfiguredRange) { - continue; - } - - String alignment = surfaceAligned ? "surface-aligned " : ""; - blockingErrors.add(context + " sampled seed " + sampled.seed() + " has an " + alignment - + "exact-Y piece envelope " + minimumYOffset + ".." + maximumYOffset - + " relative to its anchor, which cannot fit placement band " - + placementBounds.minimumY() + ".." + placementBounds.maximumY() - + " inside writable world " + worldBounds.minimumY() + ".." + worldBounds.maximumY() - + ". Native generation will not be used as a fallback."); - return; - } - } - - private static DimensionVerticalBounds resolveDimensionVerticalBounds( - JSONObject dimension, - String context, - List blockingErrors - ) { - long dimensionMinimum = -64L; - long dimensionMaximum = 320L; - if (dimension.has("dimensionHeight")) { - JSONObject dimensionHeight = dimension.optJSONObject("dimensionHeight"); - if (dimensionHeight == null) { - blockingErrors.add(context + " cannot validate its vertical envelope because dimensionHeight" - + " must be an object."); - return null; - } - Long configuredMinimum = integralJsonNumber(dimensionHeight, "min", 16L); - Long configuredMaximum = integralJsonNumber(dimensionHeight, "max", 32L); - if (configuredMinimum == null || configuredMaximum == null) { - blockingErrors.add(context + " cannot validate its vertical envelope because dimensionHeight" - + " min and max must be finite integer values."); - return null; - } - dimensionMinimum = configuredMinimum; - dimensionMaximum = configuredMaximum; - } - - long writableMinimum = dimensionMinimum + 1L; - long writableMaximum = dimensionMaximum - 1L; - if (writableMinimum > writableMaximum) { - blockingErrors.add(context + " cannot validate its vertical envelope because dimensionHeight " - + dimensionMinimum + ".." + dimensionMaximum + " has no writable structure range."); - return null; - } - return new DimensionVerticalBounds(writableMinimum, writableMaximum); - } - - private static PlacementVerticalBounds resolvePlacementVerticalBounds( - JSONObject placement, - String context, - List blockingErrors - ) { - boolean underground = false; - if (placement.has("underground")) { - Object rawUnderground = placement.opt("underground"); - if (!(rawUnderground instanceof Boolean configuredUnderground)) { - blockingErrors.add(context + " cannot validate its vertical envelope because underground" - + " must be true or false."); - return null; - } - underground = configuredUnderground; - } - Long configuredMinimum = integralJsonNumber(placement, "minHeight", -2032L); - Long configuredMaximum = integralJsonNumber(placement, "maxHeight", 2032L); - if (configuredMinimum == null || configuredMaximum == null) { - blockingErrors.add(context + " cannot validate its vertical envelope because minHeight and" - + " maxHeight must be finite integer values."); - return null; - } - long minimumY = underground - ? Math.min(configuredMinimum, configuredMaximum) : configuredMinimum; - long maximumY = underground - ? Math.max(configuredMinimum, configuredMaximum) : configuredMaximum; - return new PlacementVerticalBounds(minimumY, maximumY, underground); - } - - private static ObjectPlaceMode resolvePlaceMode( - JSONObject structure, - String context, - List blockingErrors - ) { - if (!structure.has("placeMode")) { - return ObjectPlaceMode.STRUCTURE_PIECE; - } - Object rawPlaceMode = structure.opt("placeMode"); - if (!(rawPlaceMode instanceof String placeModeName)) { - blockingErrors.add(context + " cannot validate its vertical envelope because placeMode must name" - + " an Iris object place mode."); - return null; - } - try { - return ObjectPlaceMode.valueOf(placeModeName); - } catch (IllegalArgumentException exception) { - blockingErrors.add(context + " cannot validate its vertical envelope because placeMode '" - + placeModeName + "' is not supported."); - return null; - } - } - - private static Long integralJsonNumber(JSONObject owner, String field, long defaultValue) { - if (!owner.has(field)) { - return defaultValue; - } - Object rawValue = owner.opt(field); - if (!(rawValue instanceof Number number)) { - return null; - } - double value = number.doubleValue(); - if (!Double.isFinite(value) || value != Math.rint(value) - || value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) { - return null; - } - return (long) value; - } - - private record DimensionVerticalBounds(long minimumY, long maximumY) { - } - - private record PlacementVerticalBounds(long minimumY, long maximumY, boolean underground) { - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/NativeStartPlanner.java b/src/main/java/art/arcane/iris/engine/framework/structure/NativeStartPlanner.java deleted file mode 100644 index c5f273b39..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/NativeStartPlanner.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.framework.structure; - -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.StructurePlacementGrid; -import art.arcane.iris.engine.framework.StructurePlacementScope; -import art.arcane.iris.builtin.structure.StructureAnchorMode; -import art.arcane.iris.builtin.structure.StructurePlacement; -import art.arcane.iris.builtin.structure.NativeStructureSource; -import art.arcane.volmlib.util.math.RNG; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; - -/** - * Where the pack's {@code nativeStructures} placements start platform structures: for one chunk, every placement in - * scope whose grid starts there picks a weighted source and a base height. When several placements start the same - * structure in one chunk, the placement with the lowest {@link StructurePlacementGrid#placementIdentity} (unsigned) - * wins. Seeded from the mantle seed with the selection domain the planner always used, so worlds keep their starts. - */ -public final class NativeStartPlanner { - private static final long NATIVE_SELECTION_DOMAIN = 0x4E41544956454A53L; - - private NativeStartPlanner() { - } - - /** One start a {@code nativeStructures} placement makes: the placement, its chosen source and world base Y. */ - public record Plan(StructurePlacement placement, NativeStructureSource source, int chunkX, int chunkZ, int baseY) { - } - - public static List plansAt(Engine engine, int chunkX, int chunkZ) { - Map plansByStructure = new LinkedHashMap<>(); - for (StructurePlacement placement : StructurePlacementScope.placementsAt(engine, chunkX, chunkZ)) { - Plan plan = planAt(engine, placement, chunkX, chunkZ); - if (plan == null) { - continue; - } - String structureKey = normalize(plan.source().structure()); - Plan current = plansByStructure.get(structureKey); - if (current == null || comparePlacementPriority(plan.placement(), current.placement()) < 0) { - plansByStructure.put(structureKey, plan); - } - } - return List.copyOf(plansByStructure.values()); - } - - public static Plan planAt(Engine engine, StructurePlacement placement, int chunkX, int chunkZ) { - validateBackend(placement); - if (!placement.hasNativeStructures()) { - return null; - } - Engine activeEngine = Objects.requireNonNull(engine, "Native structure planner requires an engine"); - if (activeEngine.getSeedManager() == null) { - throw new IllegalStateException("Native structure planner requires a bound seed manager"); - } - long mantleSeed = activeEngine.getSeedManager().getMantle(); - if (!StructurePlacementGrid.startsInChunk(placement, chunkX, chunkZ, mantleSeed)) { - return null; - } - RNG placementRng = StructurePlacementGrid.placementRng( - placement, chunkX, chunkZ, mantleSeed).nextParallelRNG(NATIVE_SELECTION_DOMAIN); - NativeStructureSource source = selectSource(placement.nativeStructures(), placementRng); - Integer baseY = resolveBaseY(activeEngine, placement, chunkX, chunkZ, placementRng); - if (baseY == null) { - return null; - } - return new Plan(placement, source, chunkX, chunkZ, baseY); - } - - public static void validateBackend(StructurePlacement placement) { - if (placement == null) { - throw new IllegalStateException("Structure placement must not be null"); - } - boolean iris = placement.hasIrisStructures(); - boolean nativeStructure = placement.hasNativeStructures(); - if (iris == nativeStructure) { - throw new IllegalStateException("Structure placement must declare exactly one backend: " - + "structures or nativeStructures"); - } - if (nativeStructure && placement.anchor() != StructureAnchorMode.LEGACY) { - throw new IllegalStateException("Native structure placements do not support the Iris anchor field"); - } - } - - public static boolean isSubmerged(Engine engine, int blockX, int blockZ) { - return engine.getHeight(blockX, blockZ, true) < engine.getDimension().getFluidHeight(); - } - - static NativeStructureSource selectSource(List sources, RNG rng) { - Objects.requireNonNull(sources, "Native structure sources must not be null"); - Objects.requireNonNull(rng, "Native structure selection requires an RNG"); - long totalWeight = 0L; - for (NativeStructureSource source : sources) { - if (source == null || source.structure() == null || source.structure().isBlank()) { - throw new IllegalStateException("Native structure placement contains a blank source"); - } - if (source.weight() < 1) { - throw new IllegalStateException("Native structure source '" + source.structure() - + "' has invalid weight " + source.weight()); - } - totalWeight = Math.addExact(totalWeight, source.weight()); - } - if (totalWeight > Integer.MAX_VALUE) { - throw new IllegalStateException("Native structure source weights exceed " + Integer.MAX_VALUE); - } - int roll = rng.nextInt((int) totalWeight); - for (NativeStructureSource source : sources) { - roll -= source.weight(); - if (roll < 0) { - return source; - } - } - throw new IllegalStateException("Native structure source selection produced no result"); - } - - private static Integer resolveBaseY(Engine engine, StructurePlacement placement, - int chunkX, int chunkZ, RNG rng) { - int worldMin = engine.getMinHeight() + 1; - int worldMax = engine.getMinHeight() + engine.getHeight() - 1; - if (worldMin > worldMax) { - throw new IllegalStateException("Native structure placement has invalid world height bounds"); - } - int blockX = (chunkX << 4) + 8; - int blockZ = (chunkZ << 4) + 8; - if (!placement.underwater() && isSubmerged(engine, blockX, blockZ)) { - return null; - } - if (!placement.underground()) { - int surfaceY = engine.getHeight(blockX, blockZ, true) + engine.getMinHeight(); - if (surfaceY < placement.minHeight() || surfaceY > placement.maxHeight()) { - return null; - } - return surfaceY; - } - int bandMin = Math.max(worldMin, Math.min(placement.minHeight(), placement.maxHeight())); - int bandMax = Math.min(worldMax, Math.max(placement.minHeight(), placement.maxHeight())); - if (bandMin > bandMax) { - return null; - } - return bandMin == bandMax ? bandMin : bandMin + rng.nextInt((bandMax - bandMin) + 1); - } - - private static int comparePlacementPriority(StructurePlacement left, StructurePlacement right) { - long leftIdentity = StructurePlacementGrid.placementIdentity(left); - long rightIdentity = StructurePlacementGrid.placementIdentity(right); - return Long.compareUnsigned(leftIdentity, rightIdentity); - } - - private static String normalize(String structureKey) { - return structureKey == null ? "" : structureKey.toLowerCase(Locale.ROOT); - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/PlanarJigsawWorkcellResolver.java b/src/main/java/art/arcane/iris/engine/framework/structure/PlanarJigsawWorkcellResolver.java deleted file mode 100644 index 53c3f8606..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/PlanarJigsawWorkcellResolver.java +++ /dev/null @@ -1,139 +0,0 @@ -package art.arcane.iris.engine.framework.structure; - -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcell; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.structure.IrisStructure; - -import java.util.Collections; -import java.util.EnumMap; -import java.util.Map; -import java.util.Objects; - -public final class PlanarJigsawWorkcellResolver { - public static final int DEFAULT_SIZE = 16; - public static final int MAX_WIDTH = 128; - public static final int MAX_HEIGHT = 192; - public static final int MAX_DEPTH = 128; - public static final long MAX_VOLUME = 2_097_152L; - - private PlanarJigsawWorkcellResolver() { - } - - public static Map resolve(IrisStructure structure) { - IrisStructure source = Objects.requireNonNull(structure, "Planar jigsaw structure"); - EnumMap resolved = - new EnumMap<>(IrisJigsawWorkcellArchetype.class); - if (source.getPlanarWorkcells() == null || source.getPlanarWorkcells().isEmpty()) { - IrisPosition fallback = source.getCellSize() == null - ? new IrisPosition(DEFAULT_SIZE, DEFAULT_SIZE, DEFAULT_SIZE) - : source.getCellSize(); - for (IrisJigsawWorkcellArchetype archetype : IrisJigsawWorkcellArchetype.values()) { - ResolvedWorkcell workcell = new ResolvedWorkcell( - archetype, - "", - fallback.getX(), - fallback.getY(), - fallback.getZ(), - true); - validate(workcell); - resolved.put(archetype, workcell); - } - return Collections.unmodifiableMap(resolved); - } - - for (IrisJigsawWorkcell configured : source.getPlanarWorkcells()) { - if (configured == null || configured.getArchetype() == null) { - throw new IllegalArgumentException("Planar jigsaw workcells require an archetype"); - } - ResolvedWorkcell workcell = new ResolvedWorkcell( - configured.getArchetype(), - normalizeDisplayName(configured.getDisplayName()), - configured.getWidth(), - configured.getHeight(), - configured.getDepth(), - configured.isEnabled()); - validate(workcell); - if (resolved.putIfAbsent(workcell.archetype(), workcell) != null) { - throw new IllegalArgumentException( - "Planar jigsaw workcell " + workcell.archetype() + " is configured more than once"); - } - } - if (resolved.size() != IrisJigsawWorkcellArchetype.values().length) { - for (IrisJigsawWorkcellArchetype archetype : IrisJigsawWorkcellArchetype.values()) { - if (!resolved.containsKey(archetype)) { - throw new IllegalArgumentException("Planar jigsaw workcell " + archetype + " is missing"); - } - } - } - return Collections.unmodifiableMap(resolved); - } - - public static ResolvedWorkcell workcell( - Map workcells, - IrisJigsawPiece piece - ) { - Map resolved = Objects.requireNonNull( - workcells, - "Planar jigsaw workcells"); - IrisJigsawWorkcellArchetype archetype = IrisJigsawWorkcellArchetype.fromPiece(piece); - ResolvedWorkcell workcell = resolved.get(archetype); - if (workcell == null) { - throw new IllegalArgumentException("Planar jigsaw workcell " + archetype + " is not configured"); - } - return workcell; - } - - public static IrisPosition canonicalDimensions(IrisJigsawPiece piece, IrisObject object) { - IrisJigsawPiece sourcePiece = Objects.requireNonNull(piece, "Planar jigsaw piece"); - IrisObject sourceObject = Objects.requireNonNull(object, "Planar jigsaw object"); - IrisJigsawWorkcellArchetype archetype = IrisJigsawWorkcellArchetype.fromPiece(sourcePiece); - int quarterTurns = archetype.sourceToCanonicalQuarterTurns(sourcePiece); - return Math.floorMod(quarterTurns, 2) == 0 - ? new IrisPosition(sourceObject.getW(), sourceObject.getH(), sourceObject.getD()) - : new IrisPosition(sourceObject.getD(), sourceObject.getH(), sourceObject.getW()); - } - - public record ResolvedWorkcell( - IrisJigsawWorkcellArchetype archetype, - String displayName, - int width, - int height, - int depth, - boolean enabled - ) { - public ResolvedWorkcell { - Objects.requireNonNull(archetype, "Planar jigsaw workcell archetype"); - displayName = normalizeDisplayName(displayName); - } - - public IrisPosition dimensions() { - return new IrisPosition(width, height, depth); - } - - public boolean contains(IrisPosition dimensions) { - IrisPosition size = Objects.requireNonNull(dimensions, "Planar jigsaw object dimensions"); - return size.getX() <= width && size.getY() <= height && size.getZ() <= depth; - } - } - - private static String normalizeDisplayName(String displayName) { - return displayName == null ? "" : displayName.trim(); - } - - private static void validate(ResolvedWorkcell workcell) { - if (workcell.width() < 3 || workcell.width() > MAX_WIDTH - || workcell.height() < 1 || workcell.height() > MAX_HEIGHT - || workcell.depth() < 3 || workcell.depth() > MAX_DEPTH) { - throw new IllegalArgumentException("Planar jigsaw workcell " + workcell.archetype() - + " dimensions must keep width/depth within 3..128 and height within 1..192"); - } - long volume = (long) workcell.width() * workcell.height() * workcell.depth(); - if (volume > MAX_VOLUME) { - throw new IllegalArgumentException("Planar jigsaw workcell " + workcell.archetype() - + " volume cannot exceed " + MAX_VOLUME + " blocks"); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureAssemblyResult.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureAssemblyResult.java deleted file mode 100644 index 02d7d1e87..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureAssemblyResult.java +++ /dev/null @@ -1,71 +0,0 @@ -package art.arcane.iris.engine.framework.structure; - -import art.arcane.iris.engine.framework.PlacedStructurePiece; - -import java.util.List; -import java.util.Objects; - -public record StructureAssemblyResult( - StructureAssemblyStatus status, - List pieces, - String selectedTheme, - String detail -) { - public StructureAssemblyResult { - status = Objects.requireNonNull(status, "Structure assembly status"); - pieces = List.copyOf(Objects.requireNonNull(pieces, "Structure assembly pieces")); - selectedTheme = normalize(selectedTheme); - detail = normalize(detail); - if (status == StructureAssemblyStatus.COMPLETE && pieces.isEmpty()) { - throw new IllegalArgumentException("A complete structure assembly must contain at least one piece"); - } - if (status == StructureAssemblyStatus.INTENTIONAL_EMPTY && !pieces.isEmpty()) { - throw new IllegalArgumentException("An intentionally empty structure assembly cannot contain pieces"); - } - if (status.isFailure() && detail.isEmpty()) { - throw new IllegalArgumentException("A failed structure assembly requires failure detail"); - } - } - - public static StructureAssemblyResult complete( - List pieces, - String selectedTheme - ) { - return new StructureAssemblyResult( - StructureAssemblyStatus.COMPLETE, - pieces, - selectedTheme, - ""); - } - - public static StructureAssemblyResult intentionalEmpty( - String selectedTheme, - String detail - ) { - return new StructureAssemblyResult( - StructureAssemblyStatus.INTENTIONAL_EMPTY, - List.of(), - selectedTheme, - detail); - } - - public static StructureAssemblyResult failed( - StructureAssemblyStatus status, - List pieces, - String selectedTheme, - String detail - ) { - if (Objects.requireNonNull(status, "Structure assembly failure status").isComplete()) { - throw new IllegalArgumentException("A failed structure assembly requires a failure status"); - } - return new StructureAssemblyResult(status, pieces, selectedTheme, detail); - } - - public boolean hasOutput() { - return status == StructureAssemblyStatus.COMPLETE && !pieces.isEmpty(); - } - - private static String normalize(String value) { - return value == null ? "" : value.trim(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java deleted file mode 100644 index e2ebb3068..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java +++ /dev/null @@ -1,97 +0,0 @@ -package art.arcane.iris.engine.framework.structure; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.IrisPackResources; -import art.arcane.iris.engine.framework.StructureAssembler; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.volmlib.util.math.RNG; -import com.github.benmanes.caffeine.cache.Cache; -import com.github.benmanes.caffeine.cache.Caffeine; - -import com.volmit.ModuleLog; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * Compiled structure graphs, kept per resource snapshot of the pack: every reload of the pack's resources starts a new - * snapshot ({@link IrisData#getPackResources()}), so nothing stale is ever read and nothing is invalidated by hand. - */ -public final class StructureGraphCatalog { - private static final Cache> CACHE = - Caffeine.newBuilder().weakKeys().build(); - private static final Cache> RUNTIME_OUTPUT = - Caffeine.newBuilder().weakKeys().build(); - private static final List RUNTIME_SAMPLE_SEEDS = List.of( - 0L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L, 144L, 233L, 377L, 610L, 987L); - - private StructureGraphCatalog() { - } - - public static StructureGraphCompilation compile(IrisData data, IrisStructure structure, ModuleLog log) { - IrisData activeData = Objects.requireNonNull(data); - IrisStructure activeStructure = Objects.requireNonNull(structure); - String structureKey = activeStructure.getLoadKey(); - if (structureKey == null || structureKey.isBlank()) { - return compileAndReport(activeData, activeStructure, log); - } - ConcurrentMap catalog = CACHE.get( - activeData.getPackResources(), ignored -> new ConcurrentHashMap<>()); - return catalog.computeIfAbsent(structureKey, ignored -> compileAndReport(activeData, activeStructure, log)); - } - - public static boolean guaranteesRuntimeOutput(IrisData data, IrisStructure structure, ModuleLog log) { - IrisData activeData = Objects.requireNonNull(data); - IrisStructure activeStructure = Objects.requireNonNull(structure); - if (!compile(activeData, activeStructure, log).guaranteesAssemblyOutput()) { - return false; - } - String structureKey = activeStructure.getLoadKey(); - if (structureKey == null || structureKey.isBlank()) { - return sampleRuntimeAssembly(activeData, activeStructure, log); - } - ConcurrentMap catalog = RUNTIME_OUTPUT.get( - activeData.getPackResources(), ignored -> new ConcurrentHashMap<>()); - return catalog.computeIfAbsent( - structureKey, ignored -> sampleRuntimeAssembly(activeData, activeStructure, log)); - } - - private static StructureGraphCompilation compileAndReport(IrisData data, IrisStructure structure, ModuleLog log) { - StructureGraphCompilation compilation = StructureGraphCompiler.compile( - structure, StructureGraphResolver.forData(data)); - String structureKey = structure.getLoadKey() == null || structure.getLoadKey().isBlank() - ? "" : structure.getLoadKey(); - for (StructureGraphDiagnostic diagnostic : compilation.getDiagnostics()) { - String message = "[StructureGraph:" + structureKey + "] " + diagnostic.message(); - if (diagnostic.severity() == StructureGraphDiagnostic.Severity.ERROR) { - log.error(message, null); - } else { - log.warn(message); - } - } - if (!compilation.isAssemblyViable()) { - log.error("[StructureGraph:" + structureKey - + "] Graph rejected because deterministic assembly did not complete.", null); - } - return compilation; - } - - private static boolean sampleRuntimeAssembly(IrisData data, IrisStructure structure, ModuleLog log) { - for (long seed : RUNTIME_SAMPLE_SEEDS) { - try { - StructureAssembler assembler = StructureAssembler.forData( - data, structure, new IrisPosition(0, 64, 0), log); - StructureAssemblyResult result = assembler.assemble(new RNG(seed)); - if (!result.hasOutput()) { - return false; - } - } catch (Throwable e) { - log.error("Failed to sample the runtime assembly of a structure", e); - return false; - } - } - return true; - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompilation.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompilation.java deleted file mode 100644 index c58e4a977..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompilation.java +++ /dev/null @@ -1,242 +0,0 @@ -package art.arcane.iris.engine.framework.structure; - -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet; -import art.arcane.iris.engine.object.prefab.IrisObject; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -public final class StructureGraphCompilation { - private final CompiledStructureGraph graph; - private final List diagnostics; - private final List assemblySamples; - - StructureGraphCompilation(Builder builder) { - graph = Objects.requireNonNull(builder.graph); - diagnostics = Collections.unmodifiableList(new ArrayList<>(builder.diagnostics)); - assemblySamples = Collections.unmodifiableList(new ArrayList<>(builder.assemblySamples)); - } - - static Builder builder(CompiledStructureGraph graph) { - return new Builder(graph); - } - - public CompiledStructureGraph getGraph() { - return graph; - } - - public List getDiagnostics() { - return diagnostics; - } - - public List getAssemblySamples() { - return assemblySamples; - } - - public boolean hasErrors() { - for (StructureGraphDiagnostic diagnostic : diagnostics) { - if (diagnostic.severity() == StructureGraphDiagnostic.Severity.ERROR) { - return true; - } - } - return false; - } - - public boolean isAssemblyViable() { - if (hasErrors() || assemblySamples.isEmpty()) { - return false; - } - for (StructureGraphAssemblySample sample : assemblySamples) { - if (!sample.outcome().isComplete()) { - return false; - } - } - return true; - } - - public boolean guaranteesAssemblyOutput() { - if (!isAssemblyViable()) { - return false; - } - String startPoolKey = graph.getStructure().getStartPool(); - if (startPoolKey == null || startPoolKey.isBlank()) { - return false; - } - IrisJigsawPool startPool = graph.getPools().get(startPoolKey.trim()); - if (startPool == null || startPool.getPieces() == null || startPool.getPieces().isEmpty()) { - return false; - } - for (String theme : themes()) { - if (!startPoolGuaranteesOutput(startPool, theme) - || !reachableBranchesCanTerminate(theme)) { - return false; - } - } - return true; - } - - private boolean startPoolGuaranteesOutput(IrisJigsawPool startPool, String theme) { - boolean certainPhysicalEntry = false; - for (IrisJigsawPieceEntry entry : startPool.getPieces()) { - if (entry == null || entry.getWeight() <= 0 || !Double.isFinite(entry.getChance()) - || entry.getChance() <= 0D || entry.getChance() > 1D) { - continue; - } - if (entry.isEmpty()) { - return false; - } - IrisJigsawPiece piece = graph.getPieces().get(normalize(entry.getPiece())); - if (piece == null || !JigsawPoolSelection.pieceEligible(piece, theme, 0, 0)) { - continue; - } - IrisObject object = graph.getObjects().get(normalize(piece.getObject())); - if (object == null || !fitsStartRadius(object)) { - return false; - } - if (entry.getChance() == 1D) { - certainPhysicalEntry = true; - } - } - return certainPhysicalEntry; - } - - private boolean reachableBranchesCanTerminate(String theme) { - for (String pieceKey : graph.getReachablePieces()) { - IrisJigsawPiece piece = graph.getPieces().get(pieceKey); - if (piece == null || piece.getConnectors() == null) { - return false; - } - if (!piece.supportsTheme(theme) || piece.resolvedRules().isTerminal()) { - continue; - } - for (IrisJigsawConnector connector : piece.getConnectors()) { - if (connector == null) { - return false; - } - IrisJigsawPool pool = graph.getPools().get(normalize(connector.getPool())); - if (pool == null) { - return false; - } - if (pool.requiresFallback(graph.getStructure().isRequireCaps())) { - if (!hasRequiredTerminal(pool, theme)) { - return false; - } - } else if (graph.getStructure().resolvedBranchFailurePolicy() - != IrisJigsawBranchFailurePolicy.TERMINATE_BRANCH - && !canTerminateWithoutPlacement(pool)) { - return false; - } - } - } - return true; - } - - private boolean hasRequiredTerminal(IrisJigsawPool pool, String theme) { - String fallbackKey = JigsawPoolSelection.directFallbackKey(pool); - if (fallbackKey.isEmpty()) { - return false; - } - IrisJigsawPool fallback = graph.getPools().get(fallbackKey); - if (fallback == null || fallback.getPieces() == null) { - return false; - } - for (IrisJigsawPieceEntry entry : fallback.getPieces()) { - if (entry == null || entry.isEmpty() || entry.getWeight() <= 0 || entry.getChance() != 1D) { - continue; - } - IrisJigsawPiece piece = graph.getPieces().get(normalize(entry.getPiece())); - if (piece != null && piece.supportsTheme(theme) && piece.resolvedRules().isTerminal()) { - return true; - } - } - return false; - } - - private boolean canTerminateWithoutPlacement(IrisJigsawPool pool) { - if (hasEmptyChoice(pool)) { - return true; - } - if (pool == null) { - return false; - } - String fallbackKey = JigsawPoolSelection.directFallbackKey(pool); - return !fallbackKey.isEmpty() && hasEmptyChoice(graph.getPools().get(fallbackKey)); - } - - private boolean hasEmptyChoice(IrisJigsawPool pool) { - if (pool == null || pool.getPieces() == null) { - return false; - } - if (pool.getPieces().isEmpty()) { - return true; - } - for (IrisJigsawPieceEntry entry : pool.getPieces()) { - if (entry != null && entry.getWeight() > 0 && entry.getChance() == 1D && entry.isEmpty()) { - return true; - } - } - return false; - } - - private boolean fitsStartRadius(IrisObject object) { - long radius = (long) graph.getStructure().getMaxSizeChunks() * 16L; - return axisFitsRadius(object.getW(), radius) && axisFitsRadius(object.getD(), radius); - } - - private List themes() { - if (graph.getStructure().getThemeSets() == null || graph.getStructure().getThemeSets().isEmpty()) { - return List.of(""); - } - List themes = new ArrayList<>(graph.getStructure().getThemeSets().size()); - for (IrisJigsawThemeSet theme : graph.getStructure().getThemeSets()) { - if (theme != null && theme.getKey() != null && !theme.getKey().isBlank()) { - themes.add(theme.getKey().trim()); - } - } - return List.copyOf(themes); - } - - private boolean axisFitsRadius(int size, long radius) { - if (size < 1 || radius < 1L) { - return false; - } - long minimum = -(size / 2L); - long maximum = minimum + size - 1L; - return minimum >= -radius && maximum <= radius; - } - - private String normalize(String value) { - return value == null ? "" : value.trim(); - } - - static final class Builder { - private final CompiledStructureGraph graph; - private final List diagnostics = new ArrayList<>(); - private final List assemblySamples = new ArrayList<>(); - - private Builder(CompiledStructureGraph graph) { - this.graph = Objects.requireNonNull(graph); - } - - Builder diagnostics(List values) { - diagnostics.addAll(values); - return this; - } - - Builder assemblySamples(List values) { - assemblySamples.addAll(values); - return this; - } - - StructureGraphCompilation build() { - return new StructureGraphCompilation(this); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompiler.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompiler.java deleted file mode 100644 index 94585498e..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompiler.java +++ /dev/null @@ -1,1264 +0,0 @@ -package art.arcane.iris.engine.framework.structure; - -import art.arcane.iris.engine.framework.PlacedStructurePiece; -import art.arcane.iris.engine.framework.StructureAssembler; -import art.arcane.iris.engine.object.value.IrisDirection; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawCompatibility; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawMode; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceRules; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; - -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Deque; -import java.util.HashMap; -import java.util.HashSet; -import java.util.IdentityHashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -public final class StructureGraphCompiler { - private static final int ASSEMBLY_PIECE_CAP = 512; - private static final int MAX_DEPTH = 30; - private static final int MAX_SIZE_CHUNKS = 32; - private static final int[] NO_ROTATION = {0}; - private static final int[] Y_ROTATIONS = {0, 90, 180, 270}; - private static final List ASSEMBLY_SEEDS = List.of(0L, 1L, 2L, 3L, 5L, 8L, 13L, 21L); - - private StructureGraphCompiler() { - } - - public static StructureGraphCompilation compile(IrisStructure structure, StructureGraphResolver resolver) { - CompilationState state = new CompilationState( - Objects.requireNonNull(structure), Objects.requireNonNull(resolver)); - state.loadClosure(); - state.detectFallbackCycles(); - state.analyzeReachability(); - state.validatePlanarReachableObjects(); - state.validateRuleFeasibility(); - state.validateRequiredCaps(); - CompiledStructureGraph graph = state.buildGraph(); - StructureGraphCompilation validated = StructureGraphCompilation.builder(graph) - .diagnostics(state.diagnostics()) - .build(); - List samples = state.sampleAssemblies(validated); - state.reportPieceCapSamples(samples); - return StructureGraphCompilation.builder(graph) - .diagnostics(state.diagnostics()) - .assemblySamples(samples) - .build(); - } - - private static final class CompilationState { - private final IrisStructure structure; - private final StructureGraphResolver resolver; - private final CompiledStructureGraph.Builder graph; - private final Deque pendingPools = new ArrayDeque<>(); - private final Map> poolReferences = new LinkedHashMap<>(); - private final Map> poolEntries = new LinkedHashMap<>(); - private final Map> pieceConnectors = new LinkedHashMap<>(); - private final Map pieceObjects = new LinkedHashMap<>(); - private final Set processedPools = new HashSet<>(); - private final Set missingPools = new HashSet<>(); - private final Set attemptedPieces = new HashSet<>(); - private final Set missingPieces = new HashSet<>(); - private final Set attemptedObjects = new HashSet<>(); - private final Set missingObjects = new HashSet<>(); - private final Set reachableEntries = new LinkedHashSet<>(); - private final Set reachablePieceStates = new LinkedHashSet<>(); - private final Map> reachablePiecesByTheme = new LinkedHashMap<>(); - private final Map> activeConnectors = new LinkedHashMap<>(); - private final List diagnostics = new ArrayList<>(); - private final Set diagnosticKeys = new HashSet<>(); - private Map - planarWorkcells = Map.of(); - - private CompilationState(IrisStructure structure, StructureGraphResolver resolver) { - this.structure = structure; - this.resolver = resolver; - this.graph = CompiledStructureGraph.builder(structure); - } - - private void loadClosure() { - validateStructureLimits(); - String startPool = normalize(structure.getStartPool()); - if (startPool.isEmpty()) { - addDiagnostic(StructureGraphDiagnostic.Code.MISSING_START_POOL, - "Structure '" + structureKey() + "' does not declare a start pool.", - "structure:start-pool:empty"); - return; - } - - requestPool(startPool, new PoolReference( - "Structure '" + structureKey() + "' references missing start pool '" + startPool + "'.", - StructureGraphDiagnostic.Code.MISSING_START_POOL)); - while (!pendingPools.isEmpty()) { - processPool(pendingPools.removeFirst()); - } - } - - private void validateStructureLimits() { - validateThemes(); - if (structure.getMaxDepth() < 1 || structure.getMaxDepth() > MAX_DEPTH) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_MAX_DEPTH, - "Structure '" + structureKey() + "' has maxDepth " + structure.getMaxDepth() - + "; it must be between 1 and " + MAX_DEPTH + ".", - "structure:max-depth"); - } - if (structure.getMaxSizeChunks() < 1 || structure.getMaxSizeChunks() > MAX_SIZE_CHUNKS) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_MAX_SIZE, - "Structure '" + structureKey() + "' has maxSizeChunks " + structure.getMaxSizeChunks() - + "; it must be between 1 and " + MAX_SIZE_CHUNKS + ".", - "structure:max-size"); - } - if (structure.resolvedMode() != IrisJigsawMode.PLANAR_JIGSAW) { - return; - } - try { - planarWorkcells = PlanarJigsawWorkcellResolver.resolve(structure); - } catch (IllegalArgumentException exception) { - boolean legacy = structure.getPlanarWorkcells() == null || structure.getPlanarWorkcells().isEmpty(); - addDiagnostic( - legacy - ? StructureGraphDiagnostic.Code.INVALID_PLANAR_CELL_SIZE - : StructureGraphDiagnostic.Code.INVALID_PLANAR_WORKCELL, - "Structure '" + structureKey() + "' has invalid planar workcells: " - + exception.getMessage() + ".", - "structure:planar-workcells"); - } - } - - private void validateThemes() { - KList themeSets = structure.getThemeSets(); - if (themeSets == null) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_THEME, - "Structure '" + structureKey() + "' declares a null themeSets list.", - "structure:themes:null"); - return; - } - Set keys = new LinkedHashSet<>(); - for (int index = 0; index < themeSets.size(); index++) { - IrisJigsawThemeSet theme = themeSets.get(index); - if (theme == null) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_THEME, - "Structure '" + structureKey() + "' themeSets[" + index + "] is null.", - "structure:theme:null:" + index); - continue; - } - String key = normalize(theme.getKey()); - if (key.isEmpty() || !key.equals(theme.getKey())) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_THEME, - "Structure '" + structureKey() + "' themeSets[" + index - + "] must declare a non-blank, whitespace-normalized key.", - "structure:theme:key:" + index); - } else if (!keys.add(key)) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_THEME, - "Structure '" + structureKey() + "' declares duplicate theme key '" + key + "'.", - "structure:theme:duplicate:" + key); - } - if (theme.getWeight() <= 0) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_WEIGHT, - "Structure '" + structureKey() + "' theme '" + key - + "' has non-positive weight " + theme.getWeight() + ".", - "structure:theme:weight:" + index); - } - } - if (!themeSets.isEmpty() - && structure.resolvedCompatibility() == IrisJigsawCompatibility.VANILLA_PORTABLE) { - addDiagnostic(StructureGraphDiagnostic.Code.NON_PORTABLE_METADATA, - "Structure '" + structureKey() - + "' declares coherent Iris theme sets in a VANILLA_PORTABLE graph.", - "structure:portable:themes"); - } - if (structure.isRequireCaps() - && structure.resolvedCompatibility() == IrisJigsawCompatibility.VANILLA_PORTABLE) { - addDiagnostic(StructureGraphDiagnostic.Code.NON_PORTABLE_METADATA, - "Structure '" + structureKey() - + "' requires physical terminal caps, which vanilla jigsaws cannot enforce.", - "structure:portable:require-caps"); - } - if (structure.resolvedCompatibility() == IrisJigsawCompatibility.VANILLA_PORTABLE - && structure.resolvedBranchFailurePolicy() - != IrisJigsawBranchFailurePolicy.TERMINATE_BRANCH) { - addDiagnostic(StructureGraphDiagnostic.Code.NON_PORTABLE_METADATA, - "Structure '" + structureKey() - + "' fails unresolved optional connector branches, which vanilla jigsaws terminate.", - "structure:portable:branch-failure-policy"); - } - } - - private void requestPool(String rawKey, PoolReference reference) { - String key = normalize(rawKey); - if (key.isEmpty()) { - return; - } - poolReferences.computeIfAbsent(key, ignored -> new ArrayList<>()).add(reference); - if (missingPools.contains(key)) { - addDiagnostic(reference.code(), reference.message(), "missing-pool:" + key + ":" + reference.message()); - return; - } - if (!processedPools.contains(key) && !pendingPools.contains(key)) { - pendingPools.addLast(key); - } - } - - private void processPool(String key) { - if (!processedPools.add(key)) { - return; - } - IrisJigsawPool pool = resolver.loadPool(key); - if (pool == null) { - missingPools.add(key); - for (PoolReference reference : poolReferences.getOrDefault(key, List.of())) { - addDiagnostic(reference.code(), reference.message(), - "missing-pool:" + key + ":" + reference.message()); - } - return; - } - - graph.pools().put(key, pool); - List entries = new ArrayList<>(); - poolEntries.put(key, entries); - KList configuredEntries = pool.getPieces(); - if (configuredEntries == null || configuredEntries.isEmpty()) { - if (key.equals(normalize(structure.getStartPool()))) { - addDiagnostic(StructureGraphDiagnostic.Code.EMPTY_START_POOL, - "Jigsaw pool '" + key + "' is empty.", - "empty-pool:" + key); - } - } else { - for (int index = 0; index < configuredEntries.size(); index++) { - scanPoolEntry(key, index, configuredEntries.get(index), entries); - } - } - - String fallback = JigsawPoolSelection.directFallbackKey(pool); - if (pool.isMandatoryFallback() && fallback.isEmpty()) { - addDiagnostic(StructureGraphDiagnostic.Code.MISSING_REQUIRED_FALLBACK, - "Jigsaw pool '" + key - + "' requires a direct fallback but does not declare one.", - "pool:required-fallback:" + key); - } - if (pool.isMandatoryFallback() - && structure.resolvedCompatibility() == IrisJigsawCompatibility.VANILLA_PORTABLE) { - addDiagnostic(StructureGraphDiagnostic.Code.NON_PORTABLE_METADATA, - "Jigsaw pool '" + key - + "' declares mandatoryFallback, which vanilla jigsaws cannot enforce.", - "pool:portable:mandatory-fallback:" + key); - } - if (!fallback.isEmpty()) { - requestPool(fallback, new PoolReference( - "Jigsaw pool '" + key + "' references missing fallback pool '" + fallback + "'.", - StructureGraphDiagnostic.Code.MISSING_POOL)); - } - } - - private void scanPoolEntry(String poolKey, int index, IrisJigsawPieceEntry entry, - List entries) { - if (entry == null) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_POOL_ENTRY, - "Jigsaw pool '" + poolKey + "' pieces[" + index + "] is null.", - "pool-entry:null:" + poolKey + ":" + index); - return; - } - - String pieceKey = normalize(entry.getPiece()); - PoolEntryReference entryReference = new PoolEntryReference( - poolKey, index, pieceKey, entry.getWeight(), entry.getChance(), entry.isEmpty()); - entries.add(entryReference); - if (entry.getWeight() <= 0) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_WEIGHT, - "Jigsaw pool '" + poolKey + "' pieces[" + index + "] has non-positive weight " - + entry.getWeight() + ".", - "pool-entry:weight:" + poolKey + ":" + index); - } - if (!Double.isFinite(entry.getChance()) || entry.getChance() < 0D || entry.getChance() > 1D) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_CHANCE, - "Jigsaw pool '" + poolKey + "' pieces[" + index + "] has chance " - + entry.getChance() + "; it must be finite and within 0..1.", - "pool-entry:chance:" + poolKey + ":" + index); - } - if (entry.getChance() != 1D - && structure.resolvedCompatibility() == IrisJigsawCompatibility.VANILLA_PORTABLE) { - addDiagnostic(StructureGraphDiagnostic.Code.NON_PORTABLE_METADATA, - "Jigsaw pool '" + poolKey + "' pieces[" + index - + "] declares an Iris chance gate in a VANILLA_PORTABLE graph.", - "pool-entry:portable-chance:" + poolKey + ":" + index); - } - if (entry.isEmpty()) { - if (!pieceKey.isEmpty()) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_POOL_ENTRY, - "Jigsaw pool '" + poolKey + "' pieces[" + index - + "] declares both empty=true and a piece.", - "pool-entry:ambiguous-empty:" + poolKey + ":" + index); - } - return; - } - if (pieceKey.isEmpty()) { - addDiagnostic(StructureGraphDiagnostic.Code.MISSING_PIECE, - "Jigsaw pool '" + poolKey + "' pieces[" + index + "] does not declare a piece.", - "pool-entry:piece-empty:" + poolKey + ":" + index); - return; - } - loadPiece(pieceKey, "Jigsaw pool '" + poolKey + "' pieces[" + index - + "] references missing piece '" + pieceKey + "'."); - } - - private void loadPiece(String key, String missingMessage) { - if (missingPieces.contains(key)) { - addDiagnostic(StructureGraphDiagnostic.Code.MISSING_PIECE, missingMessage, - "missing-piece:" + key + ":" + missingMessage); - return; - } - if (!attemptedPieces.add(key)) { - return; - } - - IrisJigsawPiece piece = resolver.loadPiece(key); - if (piece == null) { - missingPieces.add(key); - addDiagnostic(StructureGraphDiagnostic.Code.MISSING_PIECE, missingMessage, - "missing-piece:" + key + ":" + missingMessage); - return; - } - - graph.pieces().put(key, piece); - IrisObject object = loadPieceObject(key, piece); - validatePieceMetadata(key, piece); - scanConnectors(key, piece, object); - } - - private void validatePieceMetadata(String pieceKey, IrisJigsawPiece piece) { - KList themes = piece.getThemes(); - if (themes == null) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_THEME, - "Jigsaw piece '" + pieceKey + "' declares a null themes list.", - "piece:themes:null:" + pieceKey); - } else { - Set declaredThemes = declaredThemeKeys(); - Set seenThemes = new LinkedHashSet<>(); - for (int index = 0; index < themes.size(); index++) { - String configured = themes.get(index); - String theme = normalize(configured); - if (theme.isEmpty() || !theme.equals(configured)) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_THEME, - "Jigsaw piece '" + pieceKey + "' themes[" + index - + "] must be non-blank and whitespace-normalized.", - "piece:theme:key:" + pieceKey + ":" + index); - } else if (!seenThemes.add(theme)) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_THEME, - "Jigsaw piece '" + pieceKey + "' declares duplicate theme '" + theme + "'.", - "piece:theme:duplicate:" + pieceKey + ":" + theme); - } else if (!declaredThemes.contains(theme)) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_THEME, - "Jigsaw piece '" + pieceKey + "' references undeclared theme '" + theme + "'.", - "piece:theme:undeclared:" + pieceKey + ":" + theme); - } - } - } - - IrisJigsawPieceRules rules = piece.resolvedRules(); - boolean validDepths = rules.getMinimumDepth() >= 0 - && rules.getMaximumDepth() >= rules.getMinimumDepth() - && rules.getMaximumDepth() <= MAX_DEPTH; - boolean validPlacements = rules.getMinimumPlacements() >= 0 - && rules.getMaximumPlacements() >= 0 - && rules.getMinimumPlacements() <= ASSEMBLY_PIECE_CAP - && rules.getMaximumPlacements() <= ASSEMBLY_PIECE_CAP - && (rules.getMaximumPlacements() == 0 - || rules.getMinimumPlacements() <= rules.getMaximumPlacements()); - if (!validDepths || !validPlacements) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_PIECE_RULE, - "Jigsaw piece '" + pieceKey - + "' has invalid depth or placement-count rules.", - "piece:rules:" + pieceKey); - } - if (structure.resolvedCompatibility() == IrisJigsawCompatibility.VANILLA_PORTABLE - && (themes != null && !themes.isEmpty() || !defaultRules(rules))) { - addDiagnostic(StructureGraphDiagnostic.Code.NON_PORTABLE_METADATA, - "Jigsaw piece '" + pieceKey - + "' declares Iris theme or placement rules in a VANILLA_PORTABLE graph.", - "piece:portable:metadata:" + pieceKey); - } - } - - private Set declaredThemeKeys() { - Set themes = new LinkedHashSet<>(); - if (structure.getThemeSets() == null) { - return themes; - } - for (IrisJigsawThemeSet theme : structure.getThemeSets()) { - if (theme != null && !normalize(theme.getKey()).isEmpty()) { - themes.add(normalize(theme.getKey())); - } - } - return themes; - } - - private boolean defaultRules(IrisJigsawPieceRules rules) { - return rules.getMinimumDepth() == 0 - && rules.getMaximumDepth() == MAX_DEPTH - && rules.getMinimumPlacements() == 0 - && rules.getMaximumPlacements() == 0 - && !rules.isTerminal(); - } - - private IrisObject loadPieceObject(String pieceKey, IrisJigsawPiece piece) { - String objectKey = normalize(piece.getObject()); - pieceObjects.put(pieceKey, objectKey); - if (objectKey.isEmpty()) { - addDiagnostic(StructureGraphDiagnostic.Code.MISSING_OBJECT, - "Jigsaw piece '" + pieceKey + "' does not declare an object.", - "piece-object:empty:" + pieceKey); - return null; - } - if (missingObjects.contains(objectKey)) { - addDiagnostic(StructureGraphDiagnostic.Code.MISSING_OBJECT, - "Jigsaw piece '" + pieceKey + "' references missing object '" + objectKey + "'.", - "missing-object:" + objectKey + ":" + pieceKey); - return null; - } - if (!attemptedObjects.add(objectKey)) { - return graph.objects().get(objectKey); - } - - IrisObject object = resolver.loadObject(objectKey); - if (object == null) { - missingObjects.add(objectKey); - addDiagnostic(StructureGraphDiagnostic.Code.MISSING_OBJECT, - "Jigsaw piece '" + pieceKey + "' references missing object '" + objectKey + "'.", - "missing-object:" + objectKey + ":" + pieceKey); - return null; - } - graph.objects().put(objectKey, object); - if (object.getW() < 1 || object.getH() < 1 || object.getD() < 1) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_OBJECT_BOUNDS, - "Object '" + objectKey + "' used by jigsaw piece '" + pieceKey - + "' has invalid dimensions " + object.getW() + "x" + object.getH() + "x" - + object.getD() + ".", - "object-bounds:" + objectKey); - } - return object; - } - - private void scanConnectors(String pieceKey, IrisJigsawPiece piece, IrisObject object) { - List references = new ArrayList<>(); - pieceConnectors.put(pieceKey, references); - KList connectors = piece.getConnectors(); - if (connectors == null) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_CONNECTOR, - "Jigsaw piece '" + pieceKey + "' declares a null connector list.", - "connector-list:null:" + pieceKey); - return; - } - for (int index = 0; index < connectors.size(); index++) { - IrisJigsawConnector connector = connectors.get(index); - if (connector == null) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_CONNECTOR, - "Jigsaw piece '" + pieceKey + "' connectors[" + index + "] is null.", - "connector:null:" + pieceKey + ":" + index); - continue; - } - - boolean validDirection = connector.getDirection() != null; - if (!validDirection) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_CONNECTOR_DIRECTION, - "Jigsaw piece '" + pieceKey + "' connectors[" + index - + "] does not declare a direction.", - "connector:direction:" + pieceKey + ":" + index); - } - boolean validTop = connector.getTop() != null; - if (!validTop) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_CONNECTOR_DIRECTION, - "Jigsaw piece '" + pieceKey + "' connectors[" + index - + "] does not declare a top direction.", - "connector:top:" + pieceKey + ":" + index); - } - boolean validJoint = connector.getJoint() != null; - if (!validJoint) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_CONNECTOR, - "Jigsaw piece '" + pieceKey + "' connectors[" + index - + "] does not declare a joint type.", - "connector:joint:" + pieceKey + ":" + index); - } - boolean validPosition = isValidPosition(connector.getPosition(), object); - if (connector.getPosition() == null || object != null && !validPosition) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_CONNECTOR_POSITION, - invalidPositionMessage(pieceKey, index, connector.getPosition(), object), - "connector:position:" + pieceKey + ":" + index); - } - - boolean validNames = connector.getName() != null && connector.getTargetName() != null; - if (!validNames) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_CONNECTOR, - "Jigsaw piece '" + pieceKey + "' connectors[" + index - + "] must declare non-null name and targetName values.", - "connector:names:" + pieceKey + ":" + index); - } - - boolean validMetadata = connector.getChannel() != null - && connector.getFinalState() != null - && !connector.getFinalState().isBlank(); - if (!validMetadata) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_CONNECTOR_METADATA, - "Jigsaw piece '" + pieceKey + "' connectors[" + index - + "] must declare a channel and non-blank finalState.", - "connector:metadata:" + pieceKey + ":" + index); - } - if (structure.resolvedCompatibility() == IrisJigsawCompatibility.VANILLA_PORTABLE - && connector.getChannel() != null && !connector.getChannel().isBlank()) { - addDiagnostic(StructureGraphDiagnostic.Code.NON_PORTABLE_CONNECTOR, - "Jigsaw piece '" + pieceKey + "' connectors[" + index - + "] declares Iris-only channel '" + connector.getChannel() - + "' in a VANILLA_PORTABLE structure.", - "connector:portable-channel:" + pieceKey + ":" + index); - } - - boolean validPlanarContract = validatePlanarConnector( - pieceKey, index, connector, object, validDirection, validTop, validPosition); - - String poolKey = normalize(connector.getPool()); - if (poolKey.isEmpty()) { - addDiagnostic(StructureGraphDiagnostic.Code.MISSING_CONNECTOR_POOL, - "Jigsaw piece '" + pieceKey + "' connectors[" + index - + "] does not declare a target pool.", - "connector:pool-empty:" + pieceKey + ":" + index); - } else { - requestPool(poolKey, new PoolReference( - "Jigsaw piece '" + pieceKey + "' connectors[" + index - + "] references missing pool '" + poolKey + "'.", - StructureGraphDiagnostic.Code.MISSING_POOL)); - } - references.add(new ConnectorReference( - pieceKey, index, connector, validPosition, validDirection, validTop, validJoint, validNames, - validMetadata, validPlanarContract)); - } - } - - private boolean validatePlanarConnector(String pieceKey, int index, IrisJigsawConnector connector, - IrisObject object, boolean validDirection, boolean validTop, - boolean validPosition) { - if (structure.resolvedMode() != IrisJigsawMode.PLANAR_JIGSAW) { - return true; - } - - boolean valid = true; - if (validDirection && connector.getDirection().isVertical()) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_PLANAR_CONNECTOR, - "Jigsaw piece '" + pieceKey + "' connectors[" + index + "] uses vertical direction " - + connector.getDirection().name() - + "; planar connectors must face north, east, south," - + " or west.", - "connector:planar-direction:" + pieceKey + ":" + index); - valid = false; - } - if (validTop && connector.getTop() != IrisDirection.UP_POSITIVE_Y) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_PLANAR_CONNECTOR, - "Jigsaw piece '" + pieceKey + "' connectors[" + index + "] has top " - + connector.getTop().name() - + "; planar connectors must use UP_POSITIVE_Y to keep" - + " connected cells on one Y level.", - "connector:planar-top:" + pieceKey + ":" + index); - valid = false; - } - - if (!validDirection || connector.getDirection().isVertical() - || object == null || !validPosition) { - return valid; - } - IrisPosition objectSize = new IrisPosition(object.getW(), object.getH(), object.getD()); - IrisPosition expected = IrisJigsawConnector.canonicalPlanarPosition( - objectSize, connector.getDirection()); - if (!expected.equals(connector.getPosition())) { - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_PLANAR_CONNECTOR, - "Jigsaw piece '" + pieceKey + "' connectors[" + index + "] is at " - + connector.getPosition() + "; the canonical " + connector.getDirection().name() - + " face-center socket for object dimensions " + objectSize + " is " + expected + ".", - "connector:planar-position:" + pieceKey + ":" + index); - valid = false; - } - return valid; - } - - private String invalidPositionMessage(String pieceKey, int index, IrisPosition position, IrisObject object) { - if (position == null) { - return "Jigsaw piece '" + pieceKey + "' connectors[" + index - + "] does not declare a position."; - } - if (object == null) { - return "Jigsaw piece '" + pieceKey + "' connectors[" + index - + "] position " + position + " cannot be checked because its object is missing."; - } - return "Jigsaw piece '" + pieceKey + "' connectors[" + index + "] position " + position - + " is outside object bounds 0.." + (object.getW() - 1) + ", 0.." + (object.getH() - 1) - + ", 0.." + (object.getD() - 1) + "."; - } - - private boolean isValidPosition(IrisPosition position, IrisObject object) { - if (position == null || object == null) { - return false; - } - return position.getX() >= 0 && position.getX() < object.getW() - && position.getY() >= 0 && position.getY() < object.getH() - && position.getZ() >= 0 && position.getZ() < object.getD(); - } - - private void detectFallbackCycles() { - Map states = new HashMap<>(); - for (String poolKey : graph.pools().keySet()) { - detectFallbackCycle(poolKey, states); - } - } - - private void detectFallbackCycle(String startPool, Map states) { - if (states.getOrDefault(startPool, 0) == 2) { - return; - } - List path = new ArrayList<>(); - Map pathIndexes = new HashMap<>(); - String poolKey = startPool; - while (!poolKey.isEmpty() && graph.pools().containsKey(poolKey) - && states.getOrDefault(poolKey, 0) != 2) { - Integer cycleStart = pathIndexes.get(poolKey); - if (cycleStart != null) { - List cycle = new ArrayList<>(path.subList(cycleStart, path.size())); - cycle.add(poolKey); - String cyclePath = String.join(" -> ", cycle); - addDiagnostic(StructureGraphDiagnostic.Code.FALLBACK_CYCLE, - "Jigsaw pool fallback cycle detected: " + cyclePath + ".", - "fallback-cycle:" + cyclePath); - break; - } - pathIndexes.put(poolKey, path.size()); - path.add(poolKey); - states.put(poolKey, 1); - IrisJigsawPool pool = graph.pools().get(poolKey); - poolKey = pool == null ? "" : JigsawPoolSelection.directFallbackKey(pool); - } - for (String visitedPool : path) { - states.put(visitedPool, 2); - } - } - - private void analyzeReachability() { - String startPool = normalize(structure.getStartPool()); - if (!graph.pools().containsKey(startPool)) { - return; - } - graph.reachablePools().add(startPool); - for (String theme : reachabilityThemes()) { - analyzeThemeReachability(startPool, theme); - } - reportUnmatchedReachableConnectors(); - reportUnreachableResources(); - } - - private void analyzeThemeReachability(String startPool, String theme) { - Deque pendingPieces = new ArrayDeque<>(); - boolean viableStart = false; - for (PoolEntryReference entry : poolEntries.getOrDefault(startPool, List.of())) { - if (!entryIsViable(entry, theme, 0)) { - continue; - } - viableStart = true; - markReachableEntry(entry, theme); - if (entry.empty()) { - continue; - } - IrisJigsawPiece piece = graph.pieces().get(entry.pieceKey()); - if (piece == null) { - continue; - } - for (int rotation : rotationsFor(piece)) { - markReachablePieceState( - new PieceReachState(entry.pieceKey(), -1, rotation, 0, theme), - pendingPieces); - } - } - if (!viableStart) { - boolean disabledStart = false; - for (PoolEntryReference entry : poolEntries.getOrDefault(startPool, List.of())) { - if (!entry.empty() && entryIsResolvable(entry) && !pieceEnabled(entry.pieceKey())) { - disabledStart = true; - break; - } - } - if (disabledStart) { - addDiagnostic(StructureGraphDiagnostic.Code.NO_ENABLED_START_PIECE, - "Structure '" + structureKey() - + "' has no enabled planar workcell represented by a viable start entry.", - "structure:no-enabled-start:" + theme); - } else if (!theme.isEmpty()) { - addDiagnostic(StructureGraphDiagnostic.Code.UNSATISFIABLE_PIECE_RULE, - "Structure '" + structureKey() + "' theme '" + theme - + "' has no positive-chance start entry eligible at depth zero.", - "structure:no-theme-start:" + theme); - } else { - addDiagnostic(StructureGraphDiagnostic.Code.NO_VIABLE_START_PIECE, - "Structure '" + structureKey() + "' has no start-pool entry with a positive weight," - + " positive chance, resolvable piece, and resolvable object.", - "structure:no-viable-start"); - } - } - - while (!pendingPieces.isEmpty()) { - PieceReachState pieceState = pendingPieces.removeFirst(); - for (ConnectorReference source : pieceConnectors.getOrDefault(pieceState.pieceKey(), List.of())) { - if (source.index() == pieceState.skippedConnectorIndex() || !source.canSource()) { - continue; - } - OrientedConnector orientedSource = new OrientedConnector(source, pieceState.rotation()); - ReachableConnectorKey connectorKey = new ReachableConnectorKey( - pieceState.theme(), source.id(), pieceState.depth()); - activeConnectors.computeIfAbsent(connectorKey, ignored -> new ArrayList<>()) - .add(orientedSource); - boolean includePrimary = pieceState.depth() < Math.max(1, structure.getMaxDepth()); - int candidateDepth = Math.min( - pieceState.depth() + 1, - Math.max(1, structure.getMaxDepth())); - List candidatePools = candidatePools( - normalize(source.connector().getPool()), includePrimary); - for (String candidatePool : candidatePools) { - graph.reachablePools().add(candidatePool); - for (PoolEntryReference entry : poolEntries.getOrDefault(candidatePool, List.of())) { - if (!entryIsViable(entry, pieceState.theme(), candidateDepth)) { - continue; - } - if (entry.empty()) { - markReachableEntry(entry, pieceState.theme()); - continue; - } - List compatible = findCompatibleConnectors( - orientedSource, entry.pieceKey()); - if (!compatible.isEmpty()) { - markReachableEntry(entry, pieceState.theme()); - if (!includePrimary) { - continue; - } - for (ConnectorMatch target : compatible) { - markReachablePieceState( - new PieceReachState(entry.pieceKey(), target.connector().index(), - target.rotation(), candidateDepth, pieceState.theme()), - pendingPieces); - } - } - } - } - } - } - } - - private List reachabilityThemes() { - if (structure.getThemeSets() == null || structure.getThemeSets().isEmpty()) { - return List.of(""); - } - List themes = new ArrayList<>(structure.getThemeSets().size()); - for (IrisJigsawThemeSet theme : structure.getThemeSets()) { - if (theme != null && !normalize(theme.getKey()).isEmpty()) { - themes.add(normalize(theme.getKey())); - } - } - return themes.isEmpty() ? List.of("") : List.copyOf(themes); - } - - private void validatePlanarReachableObjects() { - if (structure.resolvedMode() != IrisJigsawMode.PLANAR_JIGSAW - || planarWorkcells.isEmpty()) { - return; - } - for (String pieceKey : graph.reachablePieces()) { - IrisJigsawPiece piece = graph.pieces().get(pieceKey); - String objectKey = pieceObjects.get(pieceKey); - IrisObject object = graph.objects().get(objectKey); - if (piece == null || object == null) { - continue; - } - PlanarJigsawWorkcellResolver.ResolvedWorkcell workcell = - PlanarJigsawWorkcellResolver.workcell(planarWorkcells, piece); - IrisPosition dimensions = PlanarJigsawWorkcellResolver.canonicalDimensions(piece, object); - if (workcell.contains(dimensions)) { - continue; - } - addDiagnostic(StructureGraphDiagnostic.Code.INVALID_PLANAR_OBJECT_SIZE, - "Object '" + objectKey + "' used by reachable planar piece '" + pieceKey - + "' is " + object.getW() + "x" + object.getH() + "x" + object.getD() - + " and canonically occupies " + dimensions.getX() + "x" + dimensions.getY() - + "x" + dimensions.getZ() + "; it does not fit " + workcell.archetype() - + " workcell " + workcell.width() + "x" + workcell.height() + "x" - + workcell.depth() + ".", - "object:planar-size:" + pieceKey); - } - } - - private void markReachableEntry(PoolEntryReference entry, String theme) { - reachableEntries.add(entry.id()); - if (!entry.empty()) { - graph.reachablePieces().add(entry.pieceKey()); - reachablePiecesByTheme.computeIfAbsent(theme, ignored -> new LinkedHashSet<>()) - .add(entry.pieceKey()); - } - } - - private void markReachablePieceState(PieceReachState state, Deque pendingPieces) { - if (!graph.reachablePieces().contains(state.pieceKey())) { - return; - } - IrisJigsawPiece piece = graph.pieces().get(state.pieceKey()); - if (piece == null || piece.resolvedRules().isTerminal()) { - return; - } - if (reachablePieceStates.add(state)) { - pendingPieces.addLast(state); - } - } - - private boolean entryIsViable(PoolEntryReference entry, String theme, int depth) { - if (!entryIsResolvable(entry)) { - return false; - } - if (entry.empty()) { - return true; - } - IrisJigsawPiece piece = graph.pieces().get(entry.pieceKey()); - return piece != null - && pieceEnabled(entry.pieceKey()) - && JigsawPoolSelection.pieceEligible(piece, theme, depth, 0); - } - - private boolean entryIsResolvable(PoolEntryReference entry) { - if (entry.weight() <= 0 || !Double.isFinite(entry.chance()) || entry.chance() <= 0D - || entry.chance() > 1D) { - return false; - } - if (entry.empty()) { - return entry.pieceKey().isEmpty(); - } - if (entry.pieceKey().isEmpty() || !graph.pieces().containsKey(entry.pieceKey())) { - return false; - } - String objectKey = pieceObjects.getOrDefault(entry.pieceKey(), ""); - return !objectKey.isEmpty() && graph.objects().containsKey(objectKey); - } - - private boolean entryIsViableForAnyTheme(PoolEntryReference entry) { - for (String theme : reachabilityThemes()) { - for (int depth = 0; depth <= Math.max(1, structure.getMaxDepth()); depth++) { - if (entryIsViable(entry, theme, depth)) { - return true; - } - } - } - return false; - } - - private boolean pieceEnabled(String pieceKey) { - if (structure.resolvedMode() != IrisJigsawMode.PLANAR_JIGSAW || planarWorkcells.isEmpty()) { - return true; - } - IrisJigsawPiece piece = graph.pieces().get(pieceKey); - return piece == null || PlanarJigsawWorkcellResolver.workcell(planarWorkcells, piece).enabled(); - } - - private void reportUnmatchedReachableConnectors() { - for (Map.Entry> active : activeConnectors.entrySet()) { - ReachableConnectorKey connectorKey = active.getKey(); - List orientations = active.getValue(); - OrientedConnector representative = orientations.getFirst(); - boolean includePrimary = connectorKey.depth() < Math.max(1, structure.getMaxDepth()); - int candidateDepth = Math.min( - connectorKey.depth() + 1, - Math.max(1, structure.getMaxDepth())); - List candidates = candidatePools( - normalize(representative.definition().getPool()), includePrimary); - boolean hasViableEntry = false; - boolean hasCompatibleEntry = false; - for (String candidatePool : candidates) { - for (PoolEntryReference entry : poolEntries.getOrDefault(candidatePool, List.of())) { - if (!entryIsViable(entry, connectorKey.theme(), candidateDepth)) { - continue; - } - hasViableEntry = true; - if (entry.empty()) { - hasCompatibleEntry = true; - break; - } - for (OrientedConnector source : orientations) { - if (!findCompatibleConnectors(source, entry.pieceKey()).isEmpty()) { - hasCompatibleEntry = true; - break; - } - } - if (hasCompatibleEntry) { - break; - } - } - if (hasCompatibleEntry) { - break; - } - } - if (hasViableEntry && !hasCompatibleEntry) { - addDiagnostic(StructureGraphDiagnostic.Code.NO_COMPATIBLE_CONNECTOR, - "Jigsaw piece '" + representative.connector().pieceKey() + "' connectors[" - + representative.connector().index() + "] targets pool '" - + normalize(representative.definition().getPool()) - + "', but no reachable candidate exposes the requested target name with a" - + " compatible direction for theme '" + themeLabel(connectorKey.theme()) + "'.", - "connector:no-match:" + representative.connector().pieceKey() + ":" - + representative.connector().index() + ":" + connectorKey.theme() - + ":" + connectorKey.depth()); - } - } - } - - private void reportUnreachableResources() { - for (String poolKey : graph.pools().keySet()) { - if (!graph.reachablePools().contains(poolKey)) { - addDiagnostic(StructureGraphDiagnostic.Code.UNREACHABLE_POOL, - "Jigsaw pool '" + poolKey + "' is in the structure closure but cannot be reached" - + " from the start pool.", - "unreachable-pool:" + poolKey); - continue; - } - for (PoolEntryReference entry : poolEntries.getOrDefault(poolKey, List.of())) { - if (!entry.empty() && entryIsViableForAnyTheme(entry) - && !reachableEntries.contains(entry.id())) { - addDiagnostic(StructureGraphDiagnostic.Code.UNREACHABLE_PIECE, - "Jigsaw pool '" + poolKey + "' pieces[" + entry.index() + "] references piece '" - + entry.pieceKey() + "', but no reachable connector can attach it.", - "unreachable-piece:" + entry.id()); - } - } - } - } - - private String themeLabel(String theme) { - return theme == null || theme.isEmpty() ? "" : theme; - } - - private List findCompatibleConnectors(OrientedConnector source, - String candidatePieceKey) { - List compatible = new ArrayList<>(); - IrisJigsawPiece candidatePiece = graph.pieces().get(candidatePieceKey); - if (candidatePiece == null) { - return compatible; - } - for (ConnectorReference candidate : pieceConnectors.getOrDefault(candidatePieceKey, List.of())) { - for (int rotation : rotationsFor(candidatePiece)) { - if (connectorsCompatible(source, candidate, rotation)) { - compatible.add(new ConnectorMatch(candidate, rotation)); - } - } - } - compatible.sort((first, second) -> Integer.compare( - second.connector().connector().getSelectionPriority(), - first.connector().connector().getSelectionPriority())); - return compatible; - } - - private boolean connectorsCompatible(OrientedConnector source, ConnectorReference candidate, - int candidateRotation) { - if (!source.connector().canSource() || !candidate.canTarget()) { - return false; - } - IrisJigsawConnector sourceConnector = source.definition(); - IrisJigsawConnector candidateConnector = candidate.connector(); - if (!Objects.equals(sourceConnector.getChannel(), candidateConnector.getChannel())) { - return false; - } - if (!Objects.equals(sourceConnector.getTargetName(), candidateConnector.getName())) { - return false; - } - - IrisDirection sourceDirection = rotateDirection( - sourceConnector.getDirection(), source.rotation()); - IrisDirection candidateDirection = rotateDirection( - candidateConnector.getDirection(), candidateRotation); - if (candidateDirection != sourceDirection.reverse()) { - return false; - } - if (sourceConnector.getJoint() != JigsawJoint.ALIGNED) { - return true; - } - IrisDirection sourceTop = rotateDirection(sourceConnector.getTop(), source.rotation()); - IrisDirection candidateTop = rotateDirection(candidateConnector.getTop(), candidateRotation); - return candidateTop == sourceTop; - } - - private List candidatePools(String firstPool, boolean includeFirst) { - List result = new ArrayList<>(); - IrisJigsawPool pool = graph.pools().get(firstPool); - if (pool == null) { - return result; - } - for (String candidate : JigsawPoolSelection.candidatePoolKeys(firstPool, pool, includeFirst)) { - if (graph.pools().containsKey(candidate)) { - result.add(candidate); - } - } - return result; - } - - private void validateRuleFeasibility() { - for (String theme : reachabilityThemes()) { - int minimumTotal = 0; - Set reachable = reachablePiecesByTheme.getOrDefault(theme, Set.of()); - for (Map.Entry entry : graph.pieces().entrySet()) { - String pieceKey = entry.getKey(); - IrisJigsawPiece piece = entry.getValue(); - if (!pieceEnabled(pieceKey) || !piece.supportsTheme(theme)) { - continue; - } - IrisJigsawPieceRules rules = piece.resolvedRules(); - if (rules.getMinimumPlacements() <= 0) { - continue; - } - minimumTotal = Math.addExact(minimumTotal, rules.getMinimumPlacements()); - if (!reachable.contains(pieceKey)) { - addDiagnostic(StructureGraphDiagnostic.Code.UNSATISFIABLE_PIECE_RULE, - "Jigsaw piece '" + pieceKey + "' requires at least " - + rules.getMinimumPlacements() + " placement(s) for theme '" - + themeLabel(theme) + "' but is not reachable for that theme.", - "piece:minimum:unreachable:" + pieceKey + ":" + theme); - } - if (rules.getMinimumDepth() > Math.max(1, structure.getMaxDepth())) { - addDiagnostic(StructureGraphDiagnostic.Code.UNSATISFIABLE_PIECE_RULE, - "Jigsaw piece '" + pieceKey + "' requires placement for theme '" - + themeLabel(theme) + "' but its minimumDepth " - + rules.getMinimumDepth() + " exceeds the structure depth boundary.", - "piece:minimum:depth:" + pieceKey + ":" + theme); - } - } - if (minimumTotal > ASSEMBLY_PIECE_CAP) { - addDiagnostic(StructureGraphDiagnostic.Code.UNSATISFIABLE_PIECE_RULE, - "Structure '" + structureKey() + "' requires " + minimumTotal - + " minimum piece placements for theme '" + themeLabel(theme) - + "', exceeding the " + ASSEMBLY_PIECE_CAP + "-piece safety cap.", - "structure:minimum-total:" + theme); - } - } - } - - private void validateRequiredCaps() { - for (Map.Entry> active : activeConnectors.entrySet()) { - ReachableConnectorKey connectorKey = active.getKey(); - List orientations = active.getValue(); - OrientedConnector representative = orientations.getFirst(); - String poolKey = normalize(representative.definition().getPool()); - IrisJigsawPool pool = graph.pools().get(poolKey); - if (pool == null || !pool.requiresFallback(structure.isRequireCaps())) { - continue; - } - String fallbackKey = JigsawPoolSelection.directFallbackKey(pool); - if (fallbackKey.isEmpty() || !graph.pools().containsKey(fallbackKey)) { - addDiagnostic(StructureGraphDiagnostic.Code.MISSING_REQUIRED_FALLBACK, - "Reachable connector '" + representative.connector().id() - + "' requires a direct fallback from pool '" + poolKey + "'.", - "connector:required-fallback:" + connectorKey); - continue; - } - int candidateDepth = Math.min( - connectorKey.depth() + 1, - Math.max(1, structure.getMaxDepth())); - boolean compatibleTerminal = false; - for (PoolEntryReference entry : poolEntries.getOrDefault(fallbackKey, List.of())) { - if (entry.empty() || !entryIsViable(entry, connectorKey.theme(), candidateDepth)) { - continue; - } - IrisJigsawPiece piece = graph.pieces().get(entry.pieceKey()); - if (piece == null || !piece.resolvedRules().isTerminal()) { - continue; - } - for (OrientedConnector source : orientations) { - if (!findCompatibleConnectors(source, entry.pieceKey()).isEmpty()) { - compatibleTerminal = true; - break; - } - } - if (compatibleTerminal) { - break; - } - } - if (!compatibleTerminal) { - addDiagnostic(StructureGraphDiagnostic.Code.NO_REQUIRED_TERMINAL, - "Direct fallback pool '" + fallbackKey + "' has no compatible positive-chance" - + " terminal piece for connector '" + representative.connector().id() - + "' and theme '" + themeLabel(connectorKey.theme()) + "'.", - "connector:required-terminal:" + connectorKey); - } - } - } - - private List sampleAssemblies(StructureGraphCompilation compilation) { - if (compilation.hasErrors()) { - return List.of(); - } - List samples = new ArrayList<>(ASSEMBLY_SEEDS.size()); - Map pieceKeys = new IdentityHashMap<>(); - for (Map.Entry entry : compilation.getGraph().getPieces().entrySet()) { - pieceKeys.put(entry.getValue(), entry.getKey()); - } - for (long seed : ASSEMBLY_SEEDS) { - try { - StructureAssembler assembler = StructureAssembler.forCompilation( - compilation, new IrisPosition(0, 64, 0)); - StructureAssemblyResult result = assembler.assemble(new RNG(seed)); - List pieces = new ArrayList<>(result.pieces().size()); - for (PlacedStructurePiece placed : result.pieces()) { - String pieceKey = pieceKeys.get(placed.getPiece()); - pieces.add(pieceKey == null ? "" : pieceKey); - } - samples.add(new StructureGraphAssemblySample( - seed, - new StructureGraphAssemblySample.Outcome( - pieces, - result.status(), - result.detail()))); - } catch (RuntimeException exception) { - addDiagnostic(StructureGraphDiagnostic.Code.ASSEMBLY_RUNTIME_FAILURE, - "Runtime assembly sampling failed at seed " + seed + ": " - + exception.getClass().getSimpleName() + ": " - + failureMessage(exception) + ".", - "assembly:runtime:" + seed); - } - } - return samples; - } - - private String failureMessage(RuntimeException exception) { - return exception.getMessage() == null || exception.getMessage().isBlank() - ? "no failure detail" : exception.getMessage(); - } - - private void reportPieceCapSamples(List samples) { - List cappedSeeds = new ArrayList<>(); - for (StructureGraphAssemblySample sample : samples) { - if (sample.outcome().pieceCapReached()) { - cappedSeeds.add(Long.toString(sample.seed())); - } - } - if (!cappedSeeds.isEmpty()) { - addDiagnostic(StructureGraphDiagnostic.Code.ASSEMBLY_PIECE_CAP_REACHED, - "Deterministic structural assembly reached the " + ASSEMBLY_PIECE_CAP - + "-piece safety cap for seeds " + String.join(", ", cappedSeeds) + ".", - "assembly:piece-cap"); - } - } - - private CompiledStructureGraph buildGraph() { - return graph.build(); - } - - private List diagnostics() { - return diagnostics; - } - - private void addDiagnostic(StructureGraphDiagnostic.Code code, String message, String deduplicationKey) { - if (diagnosticKeys.add(code.name() + ":" + deduplicationKey)) { - diagnostics.add(new StructureGraphDiagnostic(code, message)); - } - } - - private String structureKey() { - String key = structure.getLoadKey(); - return key == null || key.isBlank() ? "" : key; - } - } - - private static String normalize(String value) { - return value == null ? "" : value.trim(); - } - - private static int[] rotationsFor(IrisJigsawPiece piece) { - return piece.isRotatable() ? Y_ROTATIONS : NO_ROTATION; - } - - private static IrisDirection rotateDirection(IrisDirection direction, int degrees) { - if (direction.isVertical()) { - return direction; - } - int turns = Math.floorMod(degrees, 360) / 90; - IrisDirection rotated = direction; - for (int turn = 0; turn < turns; turn++) { - rotated = switch (rotated) { - case NORTH_NEGATIVE_Z -> IrisDirection.WEST_NEGATIVE_X; - case WEST_NEGATIVE_X -> IrisDirection.SOUTH_POSITIVE_Z; - case SOUTH_POSITIVE_Z -> IrisDirection.EAST_POSITIVE_X; - case EAST_POSITIVE_X -> IrisDirection.NORTH_NEGATIVE_Z; - case UP_POSITIVE_Y, DOWN_NEGATIVE_Y -> rotated; - }; - } - return rotated; - } - - private record PoolReference(String message, StructureGraphDiagnostic.Code code) { - } - - private record PoolEntryReference( - String poolKey, - int index, - String pieceKey, - int weight, - double chance, - boolean empty - ) { - private String id() { - return poolKey + "#" + index; - } - } - - private record ConnectorReference(String pieceKey, int index, IrisJigsawConnector connector, - boolean validPosition, boolean validDirection, boolean validTop, - boolean validJoint, boolean validNames, boolean validMetadata, - boolean validPlanarContract) { - private String id() { - return pieceKey + "#" + index; - } - - private boolean canSource() { - return canTarget() && !normalize(connector.getPool()).isEmpty(); - } - - private boolean canTarget() { - return connector != null && validPosition && validDirection && validTop && validJoint && validNames - && validMetadata && validPlanarContract; - } - } - - private record PieceReachState( - String pieceKey, - int skippedConnectorIndex, - int rotation, - int depth, - String theme - ) { - } - - private record ReachableConnectorKey(String theme, String connectorId, int depth) { - } - - private record OrientedConnector(ConnectorReference connector, int rotation) { - private IrisJigsawConnector definition() { - return connector.connector(); - } - } - - private record ConnectorMatch(ConnectorReference connector, int rotation) { - } - -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java deleted file mode 100644 index 5b96dd060..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java +++ /dev/null @@ -1,74 +0,0 @@ -package art.arcane.iris.engine.framework.structure; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; -import art.arcane.iris.engine.object.prefab.IrisObject; - -import java.util.Objects; - -public interface StructureGraphResolver { - IrisJigsawPool loadPool(String key); - - IrisJigsawPiece loadPiece(String key); - - IrisObject loadObject(String key); - - static StructureGraphResolver forData(IrisData data) { - return new IrisDataStructureGraphResolver(Objects.requireNonNull(data)); - } - - static StructureGraphResolver forCompiledGraph(CompiledStructureGraph graph) { - return new CompiledStructureGraphResolver(Objects.requireNonNull(graph)); - } -} - -final class IrisDataStructureGraphResolver implements StructureGraphResolver { - private final IrisData data; - - IrisDataStructureGraphResolver(IrisData data) { - this.data = data; - } - - @Override - public IrisJigsawPool loadPool(String key) { - return StructureResources.pool(data, key); - } - - @Override - public IrisJigsawPiece loadPiece(String key) { - return StructureResources.piece(data, key); - } - - @Override - public IrisObject loadObject(String key) { - return data.load(IrisObject.class, key, false); - } -} - -final class CompiledStructureGraphResolver implements StructureGraphResolver { - private final CompiledStructureGraph graph; - - CompiledStructureGraphResolver(CompiledStructureGraph graph) { - this.graph = graph; - } - - @Override - public IrisJigsawPool loadPool(String key) { - return graph.getPools().get(normalize(key)); - } - - @Override - public IrisJigsawPiece loadPiece(String key) { - return graph.getPieces().get(normalize(key)); - } - - @Override - public IrisObject loadObject(String key) { - return graph.getObjects().get(normalize(key)); - } - - private static String normalize(String key) { - return key == null ? "" : key.trim(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidation.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidation.java deleted file mode 100644 index a44bba695..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidation.java +++ /dev/null @@ -1,324 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.framework.structure; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.PlacedStructurePiece; -import art.arcane.iris.engine.framework.StructureAssembler; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.volmlib.util.math.RNG; -import com.volmit.resource.ResourceId; -import com.volmit.validation.Problem; -import com.volmit.validation.Severity; -import com.volmit.validation.Subject; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Checks that the structures of a pack assemble: each one's jigsaw graph is compiled, the compiler's diagnostics - * become problems, and a viable graph is assembled from every seed of {@link #GEOMETRY_SAMPLE_SEEDS} with collisions - * and radius checked. What the samples show tells {@link NativeReplacementValidation} which structures always give - * output and how far their pieces reach above and below the anchor. - *

- * Structures, pools and pieces are the pack's {@link StructureResources}; objects are read only as far as their - * bounds, straight from their files. A structure file that fails to load is skipped here: Iris's own structure graph - * check reports malformed JSON. Every problem concerns the structure's file. - */ -public final class StructureGraphValidation { - private static final List GEOMETRY_SAMPLE_SEEDS = List.of( - 0L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L, 144L, 233L, 377L, 610L, 987L); - private static final int GEOMETRY_SAMPLE_ORIGIN_Y = 64; - private static final String LEGACY_INDEX_KEY = "structure-index"; - private static final String OBJECTS_FOLDER = "objects"; - private static final String OBJECT_EXTENSION = ".iob"; - private static final String JSON_EXTENSION = ".json"; - - private StructureGraphValidation() { - } - - /** Checks every structure of the pack {@code data} holds. */ - public static Validation validate(IrisData data) { - return validate(data, null); - } - - /** Checks the structures of the pack {@code data} holds whose keys are in {@code activeStructureKeys}, or all when it is null. */ - public static Validation validate(IrisData data, Set activeStructureKeys) { - List problems = new ArrayList<>(); - Set replacementOutputStructures = new LinkedHashSet<>(); - Map> sampledVerticalEnvelopes = new LinkedHashMap<>(); - PackStructureResolver resolver = new PackStructureResolver(data); - for (ResourceId id : data.getPackResources().ids(StructureResources.STRUCTURES)) { - String structureKey = id.path(); - if (structureKey.equals(LEGACY_INDEX_KEY) || (activeStructureKeys != null && !activeStructureKeys.contains(structureKey))) { - continue; - } - IrisStructure structure = StructureResources.structure(data, structureKey); - if (structure == null) { - continue; - } - validateStructure(structure, resolver, problems, replacementOutputStructures, sampledVerticalEnvelopes); - } - return new Validation(problems, replacementOutputStructures, sampledVerticalEnvelopes); - } - - private static void validateStructure( - IrisStructure structure, - StructureGraphResolver resolver, - List problems, - Set replacementOutputStructures, - Map> sampledVerticalEnvelopes - ) { - String structureKey = structure.getLoadKey(); - Subject file = Subject.file(StructureResources.STRUCTURES.folder() + "/" + structureKey + JSON_EXTENSION); - StructureGraphCompilation compilation; - try { - compilation = StructureGraphCompiler.compile(structure, resolver); - } catch (MalformedObjectResourceException e) { - problems.add(Problem.error(file, e.getMessage())); - return; - } - for (StructureGraphDiagnostic diagnostic : compilation.getDiagnostics()) { - problems.add(diagnostic.severity() == StructureGraphDiagnostic.Severity.ERROR - ? Problem.error(file, diagnostic.message()) - : Problem.warning(file, diagnostic.message())); - } - if (!compilation.isAssemblyViable()) { - problems.add(Problem.error(file, "Structure '" + structureKey - + "' does not produce a complete deterministic assembly and will not generate" - + failedSampleSummary(compilation) + ".")); - return; - } - RuntimeGeometryValidation geometry = validateRuntimeGeometry(compilation); - if (!geometry.failures().isEmpty()) { - problems.add(Problem.error(file, "Structure '" + structureKey - + "' fails sampled collision- and radius-aware assembly: " - + String.join("; ", geometry.failures()) + ".")); - return; - } - sampledVerticalEnvelopes.put(structureKey, geometry.sampledVerticalEnvelopes()); - if (compilation.guaranteesAssemblyOutput() && geometry.outputForEverySample()) { - replacementOutputStructures.add(structureKey); - } - } - - private static RuntimeGeometryValidation validateRuntimeGeometry( - StructureGraphCompilation compilation - ) { - List failures = new ArrayList<>(); - List sampledVerticalEnvelopes = new ArrayList<>(); - boolean outputForEverySample = true; - for (long seed : GEOMETRY_SAMPLE_SEEDS) { - try { - StructureAssembler assembler = StructureAssembler.forCompilation( - compilation, new IrisPosition(0, GEOMETRY_SAMPLE_ORIGIN_Y, 0)); - StructureAssemblyResult result = assembler.assemble(new RNG(seed)); - if (result.status().isFailure()) { - failures.add("seed " + seed + " returned " + result.status() + ": " + result.detail()); - } else if (!result.hasOutput()) { - outputForEverySample = false; - } else { - sampledVerticalEnvelopes.add(sampleVerticalEnvelope(seed, result.pieces())); - } - } catch (RuntimeException e) { - failures.add("seed " + seed + " threw " + e.getClass().getSimpleName() - + ": " + failureMessage(e)); - } - } - return new RuntimeGeometryValidation( - List.copyOf(failures), outputForEverySample, List.copyOf(sampledVerticalEnvelopes)); - } - - private static SampledVerticalEnvelope sampleVerticalEnvelope( - long seed, - List pieces - ) { - int minimumY = Integer.MAX_VALUE; - int maximumY = Integer.MIN_VALUE; - for (PlacedStructurePiece piece : pieces) { - minimumY = Math.min(minimumY, piece.getMinY()); - maximumY = Math.max(maximumY, piece.getMaxY()); - } - return new SampledVerticalEnvelope( - seed, - pieces.size(), - Math.subtractExact(minimumY, GEOMETRY_SAMPLE_ORIGIN_Y), - Math.subtractExact(maximumY, GEOMETRY_SAMPLE_ORIGIN_Y)); - } - - private static Map> immutableEnvelopes( - Map> sampledVerticalEnvelopes - ) { - Map> immutable = new LinkedHashMap<>(); - for (Map.Entry> entry : sampledVerticalEnvelopes.entrySet()) { - immutable.put(entry.getKey(), List.copyOf(entry.getValue())); - } - return Map.copyOf(immutable); - } - - private static String failureMessage(RuntimeException exception) { - return exception.getMessage() == null || exception.getMessage().isBlank() - ? "no failure detail" : exception.getMessage(); - } - - private static String failedSampleSummary(StructureGraphCompilation compilation) { - List failures = new ArrayList<>(); - for (StructureGraphAssemblySample sample : compilation.getAssemblySamples()) { - if (sample.outcome().isComplete()) { - continue; - } - failures.add("seed " + sample.seed() + " placed " + sample.outcome().pieceKeys().size() - + " piece(s), status=" + sample.outcome().status() - + ": " + sample.outcome().detail()); - if (failures.size() == 3) { - break; - } - } - return failures.isEmpty() ? "" : " (" + String.join("; ", failures) + ")"; - } - - /** - * What the check found: its problems, the structures that gave output for every sample of a graph that - * guarantees output (the only ones that may replace a vanilla structure), and each viable structure's sampled - * vertical envelopes. - */ - public record Validation( - List problems, - Set replacementOutputStructures, - Map> sampledVerticalEnvelopes - ) { - public Validation { - problems = List.copyOf(problems); - replacementOutputStructures = Set.copyOf(replacementOutputStructures); - sampledVerticalEnvelopes = immutableEnvelopes(sampledVerticalEnvelopes); - } - - /** The messages of the problems that stop the pack from loading. */ - public List errors() { - return messages(Severity.ERROR); - } - - /** The messages of the problems that are only shown. */ - public List warnings() { - return messages(Severity.WARNING); - } - - private List messages(Severity severity) { - return problems.stream().filter(problem -> problem.severity() == severity).map(Problem::message).distinct().toList(); - } - } - - /** Where one sampled assembly's pieces reach, relative to its anchor. */ - public record SampledVerticalEnvelope(long seed, int pieceCount, int minimumYOffset, int maximumYOffset) { - public SampledVerticalEnvelope { - if (pieceCount <= 0) { - throw new IllegalArgumentException("Sampled vertical envelope must contain at least one piece"); - } - if (maximumYOffset < minimumYOffset) { - throw new IllegalArgumentException("Sampled vertical envelope maximum Y cannot be below minimum Y"); - } - } - } - - private record RuntimeGeometryValidation( - List failures, - boolean outputForEverySample, - List sampledVerticalEnvelopes - ) { - } - - /** Pools and pieces from the pack's structure resources; objects as far as their bounds, read from their files once each. */ - private static final class PackStructureResolver implements StructureGraphResolver { - private final IrisData data; - private final Path objectsRoot; - private final Map objects = new HashMap<>(); - private final Set missingObjects = new LinkedHashSet<>(); - - private PackStructureResolver(IrisData data) { - this.data = data; - this.objectsRoot = data.getDataFolder().toPath().toAbsolutePath().normalize().resolve(OBJECTS_FOLDER); - } - - @Override - public IrisJigsawPool loadPool(String key) { - return StructureResources.pool(data, key); - } - - @Override - public IrisJigsawPiece loadPiece(String key) { - return StructureResources.piece(data, key); - } - - @Override - public IrisObject loadObject(String key) { - if (objects.containsKey(key)) { - return objects.get(key); - } - if (missingObjects.contains(key)) { - return null; - } - Path file = resolveObject(key); - IrisObject object = file == null ? null : readObjectBounds(file); - if (object == null) { - missingObjects.add(key); - return null; - } - objects.put(key, object); - return object; - } - - private Path resolveObject(String key) { - if (key == null || key.isBlank() || key.indexOf('\\') >= 0 || key.indexOf(':') >= 0) { - return null; - } - Path file = objectsRoot.resolve(key + OBJECT_EXTENSION).normalize(); - if (!file.startsWith(objectsRoot) || !Files.isRegularFile(file)) { - return null; - } - return file; - } - - private IrisObject readObjectBounds(Path file) { - try (BufferedInputStream input = new BufferedInputStream(Files.newInputStream(file))) { - return IrisObjectFrameReader.readBounds(input, file.toString()); - } catch (IOException e) { - throw new MalformedObjectResourceException(e.getMessage(), e); - } - } - } - - private static final class MalformedObjectResourceException extends RuntimeException { - private MalformedObjectResourceException(String message, IOException cause) { - super(message, cause); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java deleted file mode 100644 index f65a38ae5..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.framework.structure; - -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.IrisStructureLocator; -import com.volmit.resource.PackResources; -import com.volmit.resource.ResourceId; -import com.volmit.service.LocateResult; -import com.volmit.service.StructureLocator; -import com.volmit.world.BlockPosition; -import com.volmit.world.PackWorld; - -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.Locale; -import java.util.Set; - -/** - * How {@code iris:structure} lets Iris find its structures: the structures of the pack's {@code structures} folder, - * the ones the world's placements assemble from jigsaw pools, and their nearest start, searched with - * {@link IrisStructureLocator}. The keys it places also name the platform structures its native placements start and - * the ones its structures stand in for; it locates those too. The platform's own locate of a natively started - * structure goes through {@link StructureVanillaStructures#locateStart} instead. - *

- * Iris's locator names structures by key: a pack structure by its pack key, a platform structure by its - * {@code namespace:path}. A key with a namespace is that id; any other is the pack's. - */ -public final class StructureLocating implements StructureLocator { - private static final char NAMESPACE_SEPARATOR = ':'; - - @Override - public Set structures(PackResources pack) { - return idsOf(pack, StructureResources.structureKeysOf(pack)); - } - - @Override - public Set locatable(PackWorld world) { - return idsOf(world.resources(), IrisStructureLocator.locatableEditableKeys(engine(world))); - } - - @Override - public Set placed(PackWorld world) { - return idsOf(world.resources(), IrisStructureLocator.placedKeysAndAliases(engine(world))); - } - - @Override - public LocateResult locate(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRadiusChunks) { - Engine engine = engine(world); - String key = keyOf(world.resources(), IrisStructureLocator.placedKeysAndAliases(engine), structure); - IrisStructureLocator.LocateResult result = IrisStructureLocator.locate(engine, key, fromX, fromZ, maxRadiusChunks); - return switch (result.status()) { - case FOUND -> LocateResult.found(new BlockPosition(result.originX(), result.baseY() - engine.getMinHeight(), result.originZ())); - case NOT_FOUND -> LocateResult.NOT_FOUND; - case SEARCH_LIMIT_REACHED -> LocateResult.SEARCH_LIMIT_REACHED; - }; - } - - private static Engine engine(PackWorld world) { - return world.extension(Engine.class).orElseThrow(); - } - - private static Set idsOf(PackResources pack, Collection keys) { - Set ids = new LinkedHashSet<>(); - for (String key : keys) { - ids.add(idOf(pack, key)); - } - return ids; - } - - private static ResourceId idOf(PackResources pack, String key) { - return key.indexOf(NAMESPACE_SEPARATOR) >= 0 ? ResourceId.parse(key.toLowerCase(Locale.ROOT)) : pack.idOf(key); - } - - /** The locator's key of {@code structure}: the placed key with that id, else the id as written. */ - private static String keyOf(PackResources pack, Collection placedKeys, ResourceId structure) { - for (String key : placedKeys) { - if (idOf(pack, key).equals(structure)) { - return key; - } - } - return structure.toString(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureResourceBundleGraphCompiler.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureResourceBundleGraphCompiler.java deleted file mode 100644 index f78a69716..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureResourceBundleGraphCompiler.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.framework.structure; - -import art.arcane.iris.core.structure.authoring.StructureResourceBundle; -import art.arcane.iris.engine.framework.StructureAssembler; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.volmlib.util.math.RNG; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -public final class StructureResourceBundleGraphCompiler { - private static final Gson GSON = new GsonBuilder().create(); - private static final List ASSEMBLY_SEEDS = List.of( - 0L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L, 144L, 233L, 377L, 610L, 987L); - - private StructureResourceBundleGraphCompiler() { - } - - public static List compile(StructureResourceBundle bundle) { - BundleGraph graph = parse(Objects.requireNonNull(bundle)); - List compilations = new ArrayList<>(graph.structures().size()); - for (IrisStructure structure : graph.structures().values()) { - compilations.add(StructureGraphCompiler.compile(structure, graph.resolver())); - } - return List.copyOf(compilations); - } - - public static void requireViable(StructureResourceBundle bundle) { - BundleGraph graph = parse(Objects.requireNonNull(bundle)); - if (graph.structures().isEmpty()) { - throw new StructureGraphValidationException("Structure bundle does not contain a root structure resource"); - } - for (IrisStructure structure : graph.structures().values()) { - StructureGraphCompilation compilation = StructureGraphCompiler.compile(structure, graph.resolver()); - if (!compilation.isAssemblyViable()) { - throw new StructureGraphValidationException( - "Structure bundle graph is not viable: " + viabilityFailure(compilation)); - } - requireGeometryViable(compilation); - } - } - - private static String viabilityFailure(StructureGraphCompilation compilation) { - for (StructureGraphDiagnostic diagnostic : compilation.getDiagnostics()) { - if (diagnostic.severity() == StructureGraphDiagnostic.Severity.ERROR) { - return diagnostic.message(); - } - } - for (StructureGraphAssemblySample sample : compilation.getAssemblySamples()) { - StructureGraphAssemblySample.Outcome outcome = sample.outcome(); - if (!outcome.isComplete()) { - return "sampled assembly at seed " + sample.seed() + " returned " - + outcome.status() + ": " + outcome.detail(); - } - } - return "deterministic assembly did not complete"; - } - - private static BundleGraph parse(StructureResourceBundle activeBundle) { - Map structures = new LinkedHashMap<>(); - Map pools = new LinkedHashMap<>(); - Map pieces = new LinkedHashMap<>(); - Map objects = new LinkedHashMap<>(); - for (StructureResourceBundle.Resource resource : activeBundle.resources().values()) { - String path = resource.relativePath(); - if (matches(path, "structures/", ".json")) { - IrisStructure structure = readJson(resource, IrisStructure.class); - String key = key(path, "structures/", ".json"); - structure.setLoadKey(key); - structures.put(key, structure); - } else if (matches(path, "jigsaw-pools/", ".json")) { - pools.put(key(path, "jigsaw-pools/", ".json"), readJson(resource, IrisJigsawPool.class)); - } else if (matches(path, "jigsaw-pieces/", ".json")) { - pieces.put(key(path, "jigsaw-pieces/", ".json"), readJson(resource, IrisJigsawPiece.class)); - } else if (matches(path, "objects/", ".iob")) { - objects.put(key(path, "objects/", ".iob"), readObjectBounds(resource)); - } - } - return new BundleGraph(structures, new BundleResolver(pools, pieces, objects)); - } - - private static void requireGeometryViable(StructureGraphCompilation compilation) { - String structureKey = compilation.getGraph().getStructureKey(); - for (long seed : ASSEMBLY_SEEDS) { - try { - StructureAssembler assembler = StructureAssembler.forCompilation( - compilation, new IrisPosition(0, 64, 0)); - StructureAssemblyResult result = assembler.assemble(new RNG(seed)); - if (result.status().isFailure()) { - throw new StructureGraphValidationException("Structure bundle graph '" + structureKey - + "' fails sampled runtime geometry assembly at seed " + seed + ": " - + result.status() + ": " + result.detail()); - } - } catch (StructureGraphValidationException e) { - throw e; - } catch (RuntimeException e) { - throw new IllegalStateException("Structure bundle graph '" + structureKey - + "' encountered an unexpected sampled runtime geometry failure at seed " + seed + ": " - + e.getClass().getSimpleName() + ": " + failureMessage(e), e); - } - } - } - - private static String failureMessage(RuntimeException exception) { - return exception.getMessage() == null || exception.getMessage().isBlank() - ? "no failure detail" : exception.getMessage(); - } - - private static boolean matches(String path, String prefix, String suffix) { - return path.startsWith(prefix) && path.endsWith(suffix) && path.length() > prefix.length() + suffix.length(); - } - - private static String key(String path, String prefix, String suffix) { - return path.substring(prefix.length(), path.length() - suffix.length()); - } - - private static T readJson(StructureResourceBundle.Resource resource, Class type) { - T value; - try { - value = GSON.fromJson(new String(resource.content(), StandardCharsets.UTF_8), type); - } catch (RuntimeException e) { - throw new StructureGraphValidationException("Malformed structure resource " + resource.relativePath(), e); - } - if (value == null) { - throw new StructureGraphValidationException("Empty structure resource " + resource.relativePath()); - } - return value; - } - - private static IrisObject readObjectBounds(StructureResourceBundle.Resource resource) { - try (ByteArrayInputStream input = new ByteArrayInputStream(resource.content())) { - return IrisObjectFrameReader.readBounds(input, resource.relativePath()); - } catch (IOException e) { - throw new StructureGraphValidationException(e.getMessage(), e); - } - } - - private record BundleResolver( - Map pools, - Map pieces, - Map objects - ) implements StructureGraphResolver { - private BundleResolver { - pools = Map.copyOf(pools); - pieces = Map.copyOf(pieces); - objects = Map.copyOf(objects); - } - - @Override - public IrisJigsawPool loadPool(String key) { - return pools.get(key); - } - - @Override - public IrisJigsawPiece loadPiece(String key) { - return pieces.get(key); - } - - @Override - public IrisObject loadObject(String key) { - return objects.get(key); - } - } - - private record BundleGraph(Map structures, BundleResolver resolver) { - private BundleGraph { - structures = Map.copyOf(structures); - Objects.requireNonNull(resolver); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java deleted file mode 100644 index a5504fa6c..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.framework.structure; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.IrisPackResources; -import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; -import com.volmit.resource.PackResources; -import com.volmit.resource.ResourceId; -import com.volmit.resource.ResourceKind; - -import java.util.List; - -/** - * The resource kinds of Iris's module {@code iris:structure-model}, which keep the folders and files Iris packs have always used, - * and lookups by pack key for code that still names structures, pools and pieces by key. Every lookup goes through - * the pack's {@link com.volmit.resource.PackResources}, so it sees the pack's current snapshot: a hotload, or - * {@link IrisData#invalidateStructureResources()} after a tool rewrote the files, reads them again. - *

- * Lookups answer null where Iris's loaders did: for a blank key, a key the pack has no file for, and a file that - * fails to load, which was reported when it was read. - */ -public final class StructureResources { - /** Jigsaw structures, in {@code structures/}. */ - public static final ResourceKind STRUCTURES = ResourceKind.of("iris:structure-model/structure", "structures", IrisStructure.class); - /** Jigsaw pools a structure starts from and connectors lead to, in {@code jigsaw-pools/}. */ - public static final ResourceKind POOLS = ResourceKind.of("iris:structure-model/pool", "jigsaw-pools", IrisJigsawPool.class); - /** Jigsaw pieces pools hold, each an object with connectors, in {@code jigsaw-pieces/}. */ - public static final ResourceKind PIECES = ResourceKind.of("iris:structure-model/piece", "jigsaw-pieces", IrisJigsawPiece.class); - - private StructureResources() { - } - - /** Every resource kind of the structure model. */ - public static List> kinds() { - return List.of(STRUCTURES, POOLS, PIECES); - } - - public static IrisStructure structure(IrisData data, String key) { - return find(data, STRUCTURES, key); - } - - public static IrisJigsawPool pool(IrisData data, String key) { - return find(data, POOLS, key); - } - - public static IrisJigsawPiece piece(IrisData data, String key) { - return find(data, PIECES, key); - } - - /** The key of every structure of the pack, in key order. */ - public static List structureKeys(IrisData data) { - return structureKeysOf(data.getPackResources()); - } - - /** The key of every structure of the pack snapshot {@code pack}, in key order. */ - public static List structureKeysOf(PackResources pack) { - return keys(pack, STRUCTURES); - } - - /** The key of every jigsaw piece of the pack, in key order. */ - public static List pieceKeys(IrisData data) { - return keys(data, PIECES); - } - - private static T find(IrisData data, ResourceKind kind, String key) { - if (key == null || key.isBlank()) { - return null; - } - IrisPackResources resources = data.getPackResources(); - try { - return resources.find(kind, resources.idOf(key)).orElse(null); - } catch (IllegalStateException failedToLoad) { - return null; - } - } - - /** A key's id has the key as its path, so the path names the resource again wherever a key is expected. */ - private static List keys(IrisData data, ResourceKind kind) { - return keys(data.getPackResources(), kind); - } - - private static List keys(PackResources pack, ResourceKind kind) { - return pack.ids(kind).stream().map(ResourceId::path).toList(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureValidator.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureValidator.java deleted file mode 100644 index d98603420..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureValidator.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.framework.structure; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.IrisValidationContext; -import art.arcane.iris.core.pack.PackValidationIo; -import art.arcane.volmlib.util.json.JSONArray; -import art.arcane.volmlib.util.json.JSONObject; -import com.volmit.validation.ValidationContext; -import com.volmit.validation.Validator; - -import java.io.File; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -/** - * Module {@code iris:structure}'s check of a pack: every structure a dimension, region or biome places must assemble - * ({@link StructureGraphValidation}), and a dimension that replaces a vanilla structure with an Iris one may only use - * structures that always assemble and fit ({@link NativeReplacementValidation}). Graph diagnostics keep their - * severity; everything else is an error, as when Iris's own pack validator ran these checks. - */ -public final class StructureValidator implements Validator { - private static final List STRUCTURE_HOST_FOLDERS = List.of("dimensions", "regions", "biomes"); - private static final String STRUCTURES_FIELD = "structures"; - - @Override - public void validate(ValidationContext pack) { - IrisData data = IrisValidationContext.of(pack).data(); - StructureGraphValidation.Validation graphs = StructureGraphValidation.validate(data, placedStructureKeys(data.getDataFolder())); - graphs.problems().forEach(pack::report); - NativeReplacementValidation.validate(data.getDataFolder(), graphs.replacementOutputStructures(), graphs.sampledVerticalEnvelopes()) - .forEach(pack::report); - } - - /** - * The keys of the structures the dimension, region and biome files of the pack in {@code packFolder} place, read - * from their JSON as written, like the other checks of these files. - */ - public static Set placedStructureKeys(File packFolder) { - Set structureKeys = new LinkedHashSet<>(); - if (packFolder == null || !packFolder.isDirectory()) { - return structureKeys; - } - for (String folderName : STRUCTURE_HOST_FOLDERS) { - File resourceFolder = new File(packFolder, folderName); - if (!resourceFolder.isDirectory()) { - continue; - } - for (File resourceFile : PackValidationIo.listJsonRecursive(resourceFolder)) { - addPlacedKeys(structureKeys, PackValidationIo.readJson(resourceFile)); - } - } - return Set.copyOf(structureKeys); - } - - private static void addPlacedKeys(Set structureKeys, JSONObject resource) { - JSONArray placements = resource == null ? null : resource.optJSONArray(STRUCTURES_FIELD); - if (placements == null) { - return; - } - for (int placementIndex = 0; placementIndex < placements.length(); placementIndex++) { - JSONObject placement = placements.optJSONObject(placementIndex); - JSONArray references = placement == null ? null : placement.optJSONArray(STRUCTURES_FIELD); - if (references == null) { - continue; - } - for (int referenceIndex = 0; referenceIndex < references.length(); referenceIndex++) { - if (references.opt(referenceIndex) instanceof String structureKey && !structureKey.isBlank()) { - structureKeys.add(structureKey); - } - } - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java deleted file mode 100644 index 5c7702f88..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.framework.structure; - -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.IrisStructureLocator; -import art.arcane.iris.engine.framework.StructurePlacementGrid; -import art.arcane.iris.engine.framework.structure.fit.StartLayouts; -import art.arcane.iris.engine.framework.structure.fit.StructureFitting; -import art.arcane.iris.builtin.structure.StructurePlacement; -import art.arcane.iris.builtin.structure.NativeStructureSuppression; -import com.volmit.resource.ResourceId; -import com.volmit.service.LocateResult; -import com.volmit.service.VanillaStructures; -import com.volmit.vanilla.PlatformStart; -import com.volmit.vanilla.StartMemo; -import com.volmit.vanilla.StartReach; -import com.volmit.vanilla.StructureFit; -import com.volmit.vanilla.VanillaStructureContext; -import com.volmit.vanilla.VanillaStructureRule; -import com.volmit.vanilla.VanillaStructureSetup; -import com.volmit.vanilla.VanillaStructureStart; -import com.volmit.vanilla.VanillaStructureStartContext; -import com.volmit.world.BlockPosition; -import com.volmit.world.PackWorld; - -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Locale; -import java.util.Optional; -import java.util.Set; - -/** - * What {@code iris:structure} says about the platform's own structures. The dimension's {@code importedStructures} - * settings ({@link ImportedStructures}) disable, move, fit and set them up; the pack's structure placements replace - * them ({@code vanillaSource} with native suppression), place them alongside ({@link IrisStructureLocator#isPlaced}), - * start them where their {@code nativeStructures} grids say ({@link NativeStartPlanner}) and fit those starts the way - * the placement says, which their memo carries to every chunk they reach ({@link StructureFitting}). It names the - * structures its native placements start and finds their starts for the platform's own locate. - */ -public final class StructureVanillaStructures implements VanillaStructures { - /** - * {@link VanillaStructureRule#REPLACE} for a structure an Iris structure replaces or the dimension disables while a - * placement places it, {@link VanillaStructureRule#BLOCK} for one the dimension disables, and - * {@link VanillaStructureRule#ALSO_PLACE} for one a placement places alongside the platform. - */ - @Override - public VanillaStructureRule rule(ResourceId structure, VanillaStructureContext context) { - Engine engine = context.settings().extension(Engine.class).orElseThrow(); - String key = structure.toString(); - boolean replaced = IrisStructureLocator.suppressesVanilla(engine, key); - boolean blocked = replaced || ImportedStructures.of(context.settings()).disables(key); - boolean placed = replaced || IrisStructureLocator.isPlaced(engine, key); - VanillaStructureRule rule = blocked ? VanillaStructureRule.BLOCK : VanillaStructureRule.GENERATE; - return placed ? rule.and(VanillaStructureRule.ALSO_PLACE) : rule; - } - - @Override - public List starts(int chunkX, int chunkZ, VanillaStructureStartContext context) { - Engine engine = engine(context.world()); - return NativeStartPlanner.plansAt(engine, chunkX, chunkZ).stream() - .map(plan -> start(plan, engine.getMinHeight())) - .toList(); - } - - @Override - public int shift(PlatformStart start, VanillaStructureContext context) { - return StartLayouts.shift(start, ImportedStructures.of(context.settings()) - .adjustment(start.structure().toString(), start.underground())); - } - - @Override - public StartReach reach(ResourceId structure, boolean underground, Optional memo, - VanillaStructureContext context) { - NativeStructureFit fit = memo.map(NativeStructureFit::of) - .orElseGet(() -> ImportedStructures.of(context.settings()).adjustment(structure.toString(), underground)); - return StartLayouts.reach(fit.resolvedTerrain()); - } - - @Override - public void beforePieces(StructureFit fit) { - StructureFitting.beforePieces(fit); - } - - @Override - public void afterPieces(StructureFit fit, StructureFit.Start placed) { - StructureFitting.afterPieces(fit, placed); - } - - @Override - public VanillaStructureSetup setup(VanillaStructureContext context) { - return ImportedStructures.of(context.settings()).setup(); - } - - @Override - public Set startedStructures(PackWorld world) { - return structureIds(IrisStructureLocator.nativeKeys(engine(world))); - } - - @Override - public Set locatableStarts(PackWorld world) { - return structureIds(IrisStructureLocator.locatableNativeKeys(engine(world))); - } - - /** Searches the rings of the placements that start {@code structure} natively, as the platform's own locate does. */ - @Override - public LocateResult locateStart(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRings, - ChunkFilter accepts) { - Engine engine = engine(world); - IrisStructureLocator.LocateResult result = IrisStructureLocator.locateInPlacementRings( - engine, structure.toString(), fromX, fromZ, maxRings, accepts::accepts); - return switch (result.status()) { - case FOUND -> LocateResult.found(new BlockPosition(result.originX(), result.baseY() - engine.getMinHeight(), result.originZ())); - case NOT_FOUND -> LocateResult.NOT_FOUND; - case SEARCH_LIMIT_REACHED -> LocateResult.SEARCH_LIMIT_REACHED; - }; - } - - private static Engine engine(PackWorld world) { - return world.extension(Engine.class).orElseThrow(); - } - - private static Set structureIds(Set keys) { - Set ids = new LinkedHashSet<>(); - for (String key : keys) { - ids.add(ResourceId.parse(key.toLowerCase(Locale.ROOT))); - } - return ids; - } - - /** {@code plan} as the start the platform generates: heights above the bottom, the placement's identity and fit. */ - static VanillaStructureStart start(NativeStartPlanner.Plan plan, int minHeight) { - StructurePlacement placement = plan.placement(); - NativeStructureFit fit = new NativeStructureFit(0, null, false, placement.stilt().orElse(null), placement.resolvedTerrain()); - VanillaStructureStart start = VanillaStructureStart.at(ResourceId.parse(plan.source().structure()), - plan.chunkX(), plan.chunkZ(), plan.baseY() - minHeight) - .withIdentity(StructurePlacementGrid.placementIdentity(placement)) - .withMemo(fit.memo()); - if (placement.underground()) { - start = start.underground(); - } - if (placement.nativeSuppression() == NativeStructureSuppression.REPLACE_SOURCE) { - start = start.replacingPlatformStart(); - } - return plan.source().jigsaw().map(start::withJigsaw).orElse(start); - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/CarveFootprints.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/CarveFootprints.java deleted file mode 100644 index e2f29c440..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/fit/CarveFootprints.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.framework.structure.fit; - -import art.arcane.iris.engine.mantle.components.StructureCarvingFootprint; -import com.volmit.vanilla.StartKey; - -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.WeakHashMap; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Per-column occupancy of whole starts for organic carving, kept because a structure spans many chunks and every one of - * them carves against the same shrinkwrapped footprint. Keyed weakly on the platform's own key of the start, so retired - * starts (world unload, generation done) are collectable; values hold only primitives, so no value pins its key. The - * cached cells stay inside a budget, the oldest starts giving way first. - */ -final class CarveFootprints { - private static final int MAX_CACHED_CARVE_CELLS = 2_000_000; - private static final int MAX_CARVE_COLUMNS = 2_000_000; - private static final Map> CARVE_FOOTPRINTS = new WeakHashMap<>(16); - private static final ConcurrentHashMap> BUILDS = - new ConcurrentHashMap<>(); - private static int cachedCarveCells; - - private CarveFootprints() { - } - - static StructureCarvingFootprint of(FitStart start, int horizontalPadding) { - CarveFootprintKey key = new CarveFootprintKey(start.key(), horizontalPadding); - StructureCarvingFootprint cached = cached(key); - if (cached != null) { - return cached; - } - CompletableFuture build = new CompletableFuture<>(); - CompletableFuture active = BUILDS.putIfAbsent(key, build); - if (active != null) { - return await(active); - } - // Close the check-then-claim window: a racer whose cache check missed before the previous builder cached can - // claim the build slot after that builder retired it, and would rebuild a second instance without this re-check. - StructureCarvingFootprint published = cached(key); - if (published != null) { - build.complete(published); - BUILDS.remove(key, build); - return published; - } - try { - StructureCarvingFootprint footprint = StructureCarvingFootprint.fromColumns(sink -> { - for (FitPiece piece : start.pieces()) { - piece.columns(sink::column); - } - return true; - }, horizontalPadding, MAX_CARVE_COLUMNS); - if (footprint == null) { - throw new IllegalStateException("Native structure carve footprint is empty or exceeds " - + MAX_CARVE_COLUMNS + " columns"); - } - cache(key, footprint); - build.complete(footprint); - return footprint; - } catch (RuntimeException | Error error) { - build.completeExceptionally(error); - throw error; - } finally { - BUILDS.remove(key, build); - } - } - - static int cachedCells() { - synchronized (CARVE_FOOTPRINTS) { - cachedCarveCells = liveCells(); - return cachedCarveCells; - } - } - - static int maximumCachedCells() { - return MAX_CACHED_CARVE_CELLS; - } - - private static int liveCells() { - int total = 0; - for (Map perStart : CARVE_FOOTPRINTS.values()) { - for (CachedCarveFootprint cached : perStart.values()) { - total += cached.cells(); - } - } - return total; - } - - private static StructureCarvingFootprint cached(CarveFootprintKey key) { - synchronized (CARVE_FOOTPRINTS) { - Map perStart = CARVE_FOOTPRINTS.get(key.start()); - CachedCarveFootprint cached = perStart == null ? null : perStart.get(key.padding()); - return cached == null ? null : cached.footprint(); - } - } - - /** The loser of a build race surfaces the builder's own exception, not a CompletionException wrapper. */ - private static StructureCarvingFootprint await(CompletableFuture future) { - try { - return future.join(); - } catch (CompletionException error) { - Throwable cause = error.getCause(); - if (cause instanceof RuntimeException runtime) { - throw runtime; - } - if (cause instanceof Error fatal) { - throw fatal; - } - if (cause == null) { - throw error; - } - throw new IllegalStateException("Native structure carve footprint build failed", cause); - } - } - - private static void cache(CarveFootprintKey key, StructureCarvingFootprint footprint) { - int cells = Math.multiplyExact(footprint.width(), footprint.depth()); - synchronized (CARVE_FOOTPRINTS) { - // Weak keys expunge silently as the GC drops retired starts; re-derive the live total so the cell budget - // tracks reality instead of drifting. - cachedCarveCells = liveCells(); - Map perStart = - CARVE_FOOTPRINTS.computeIfAbsent(key.start(), ignored -> new LinkedHashMap<>(4)); - CachedCarveFootprint previous = perStart.remove(key.padding()); - if (previous != null) { - cachedCarveCells -= previous.cells(); - } - Iterator>> eviction = - CARVE_FOOTPRINTS.entrySet().iterator(); - while (cachedCarveCells + cells > MAX_CACHED_CARVE_CELLS && eviction.hasNext()) { - Map.Entry> victim = eviction.next(); - if (victim.getKey() == key.start()) { - continue; - } - for (CachedCarveFootprint evicted : victim.getValue().values()) { - cachedCarveCells -= evicted.cells(); - } - eviction.remove(); - } - perStart.put(key.padding(), new CachedCarveFootprint(footprint, cells)); - cachedCarveCells += cells; - } - } - - /** A start's key is equal only to itself, so the key pins the exact start a chunk carves against. */ - private record CarveFootprintKey(StartKey start, int padding) { - } - - private record CachedCarveFootprint(StructureCarvingFootprint footprint, int cells) { - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/StructureFitting.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/StructureFitting.java deleted file mode 100644 index 9bc5992ea..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/fit/StructureFitting.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.framework.structure.fit; - -import art.arcane.iris.builtin.structure.StructureStilts; -import art.arcane.iris.engine.framework.structure.ImportedStructures; -import art.arcane.iris.engine.framework.structure.NativeStructureFit; -import com.volmit.block.BlockState; -import com.volmit.block.PaletteSpec; -import com.volmit.vanilla.StructureFit; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.IntBinaryOperator; - -/** - * How {@code iris:structure} fits the platform's starts into one chunk. Before any piece is placed it fits the - * surface around SOURCE beard and VACUUM starts, integrates the terrain of every start and bridges short gaps between - * rigid pieces; after each start's pieces it builds that start's stilts, and after the last one it repairs the gaps - * left under VACUUM foundations. A start the module placed itself is fitted the way its memo records; one of the - * platform's own starts the way the dimension's {@code importedStructures} adjust it today. - */ -public final class StructureFitting { - private StructureFitting() { - } - - public static void beforePieces(StructureFit fit) { - chunkOf(fit).prepare(); - } - - public static void afterPieces(StructureFit fit, StructureFit.Start placed) { - ChunkFit chunk = chunkOf(fit); - chunk.buildStilts(placed); - if (placed == fit.starts().getLast()) { - chunk.repairFoundations(); - } - } - - private static ChunkFit chunkOf(StructureFit fit) { - return fit.state(ChunkFit.class, () -> new ChunkFit(fit)); - } - - /** One chunk's fit: its starts with their resolved fits, and the foundations VACUUM raised the terrain to. */ - private static final class ChunkFit { - private final StructureFit fit; - private final FitBlocks blocks; - private final Box area; - private final List starts; - private final IntBinaryOperator surfaceHeight; - private SurfaceFitting.VacuumFoundationPlan vacuumFoundations = SurfaceFitting.VacuumFoundationPlan.EMPTY; - - private ChunkFit(StructureFit fit) { - this.fit = fit; - this.blocks = new FitBlocks(fit.blocks(), fit.bottomY()); - this.area = Box.of(fit.area(), fit.bottomY()); - this.starts = resolvedStarts(fit); - this.surfaceHeight = (x, z) -> fit.surfaceY(x, z) + fit.bottomY(); - } - - private static List resolvedStarts(StructureFit fit) { - List starts = new ArrayList<>(fit.starts().size()); - for (StructureFit.Start start : fit.starts()) { - starts.add(new FitStart(start, fitOf(fit, start), fit.bottomY())); - } - return List.copyOf(starts); - } - - private static NativeStructureFit fitOf(StructureFit fit, StructureFit.Start start) { - return start.memo() - .map(NativeStructureFit::of) - .orElseGet(() -> ImportedStructures.of(fit.world().settings()) - .adjustment(start.structure().toString(), start.step().isUnderground())); - } - - private void prepare() { - vacuumFoundations = SurfaceFitting.prepareSurfaceStructures(blocks, area, starts, surfaceHeight, - SurfaceFitting.MAX_SURFACE_TEMPLATE_CELLS, fit.log()); - TerrainIntegration.prepareTerrain(blocks, area, starts, fit.seed(), this::naturalBlock, this::paletteBlock); - RigidSupport.bridgeRigidPieceSupport(blocks, area, starts); - } - - private void buildStilts(StructureFit.Start placed) { - FitStart start = fitStartOf(placed); - StructureStilts stilts = start.fit().stilts(); - if (stilts == null) { - return; - } - FoundationStilts.placeStilts(blocks, area, start, stilts, fit.seed(), this::paletteBlock, surfaceHeight, - !start.step().isUnderground()); - } - - private void repairFoundations() { - SurfaceFitting.repairVacuumFoundations(blocks, area, vacuumFoundations); - } - - private FitStart fitStartOf(StructureFit.Start placed) { - for (FitStart start : starts) { - if (start.start() == placed) { - return start; - } - } - throw new IllegalArgumentException("Start " + placed.structure() + " is not one of the chunk's starts"); - } - - private BlockState naturalBlock(int worldY) { - return fit.naturalBlock(worldY - fit.bottomY()); - } - - private BlockState paletteBlock(PaletteSpec palette, long seed, int x, int y, int z) { - return fit.world().resources().blocks().palette(palette, seed).at(x, y, z); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegration.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegration.java deleted file mode 100644 index 74687fcf6..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegration.java +++ /dev/null @@ -1,633 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.framework.structure.fit; - -import art.arcane.iris.builtin.structure.StructureCarveShape; -import art.arcane.iris.builtin.structure.StructureTerrain; -import art.arcane.iris.builtin.structure.StructureTerrainMode; -import art.arcane.iris.engine.mantle.components.StructureCarveEnvelope; -import art.arcane.iris.engine.mantle.components.StructureCarvingFootprint; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.math.RNG; -import com.volmit.block.BlockState; -import com.volmit.block.PaletteSpec; -import com.volmit.resource.ResourceId; -import com.volmit.vanilla.TerrainAdaptation; -import com.volmit.world.BlockPosition; - -import java.util.BitSet; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.function.IntFunction; - -/** - * The terrain fitting that runs before a start's pieces are placed, for every mode but VACUUM: SOURCE replays the - * platform's BURY and ENCAPSULATE adaptations by filling the envelope around rigid pieces with the nearby natural - * material, ENCASE fills the padded piece boxes, BORE clears them, FORCE_CARVE clears a box or a rounded, optionally - * eroded shape around the pieces' silhouette. Legacy templates then clear their authored air over the terrain. - */ -final class TerrainIntegration { - private static final long CARVE_CEILING_ROLL_SIGNATURE = 0x2A17L; - private static final long CARVE_FLOOR_ROLL_SIGNATURE = 0x5B3DL; - private static final long CARVE_LOBE_SIGNATURE = 0x7C41L; - private static final long CARVE_IDENTITY_X = 341873128712L; - private static final long CARVE_IDENTITY_Z = 132897987541L; - private static final int SOURCE_BURY_HORIZONTAL_RADIUS = 6; - private static final int SOURCE_BURY_VERTICAL_RADIUS = 12; - private static final int SOURCE_ENCAPSULATE_RADIUS = 12; - private static final int SOURCE_JUNCTION_RADIUS = 12; - private static final int SOURCE_MATERIAL_SAMPLE_RADIUS = 8; - private static final Set VANILLA_SOURCE_TERRAIN_BLOCKS = Set.of( - "minecraft:stone", "minecraft:granite", "minecraft:diorite", "minecraft:andesite", - "minecraft:tuff", "minecraft:deepslate", "minecraft:netherrack", "minecraft:basalt", - "minecraft:blackstone", "minecraft:dirt", "minecraft:coarse_dirt", "minecraft:rooted_dirt", - "minecraft:grass_block", "minecraft:podzol", "minecraft:mycelium", "minecraft:mud", - "minecraft:moss_block", "minecraft:sand", "minecraft:red_sand", "minecraft:terracotta", - "minecraft:crimson_nylium", "minecraft:warped_nylium", "minecraft:snow_block", - "minecraft:ice", "minecraft:packed_ice", "minecraft:blue_ice", "minecraft:soul_sand", - "minecraft:soul_soil", "minecraft:end_stone", "minecraft:gravel", "minecraft:clay", - "minecraft:calcite", "minecraft:dripstone_block", "minecraft:sandstone", - "minecraft:red_sandstone", "minecraft:sculk"); - private static final List SOURCE_TERRAIN_TAGS = List.of( - ResourceId.parse("minecraft:base_stone_overworld"), ResourceId.parse("minecraft:base_stone_nether"), - ResourceId.parse("minecraft:substrate_overworld"), ResourceId.parse("minecraft:dirt"), - ResourceId.parse("minecraft:sand"), ResourceId.parse("minecraft:terracotta"), - ResourceId.parse("minecraft:mud"), ResourceId.parse("minecraft:moss_blocks"), - ResourceId.parse("minecraft:grass_blocks"), ResourceId.parse("minecraft:nylium"), - ResourceId.parse("minecraft:snow"), ResourceId.parse("minecraft:ice"), - ResourceId.parse("minecraft:coral_blocks"), ResourceId.parse("minecraft:soul_fire_base_blocks")); - - private TerrainIntegration() { - } - - /** - * Integrates the terrain of every start, then clears the legacy template air of those that replay their own - * adaptation or are encased. The natural material SOURCE fills with is read once for all starts, before any fill. - */ - static void prepareTerrain(FitBlocks blocks, Box area, List starts, long seed, - IntFunction naturalBlock, FitPalettes palettes) { - if (starts.isEmpty()) { - return; - } - SourceTerrainSnapshot sourceTerrain = captureSourceTerrain(blocks, area, starts); - for (FitStart start : starts) { - integrateTerrain(blocks, area, start, seed, naturalBlock, palettes, sourceTerrain); - } - for (FitStart start : starts) { - if (clearsLegacyTemplateAir(start)) { - clearLegacyTemplateAir(blocks, area, start); - } - } - } - - static void integrateTerrain(FitBlocks blocks, Box area, FitStart start, long seed, - IntFunction naturalBlock, FitPalettes palettes, - SourceTerrainSnapshot sourceTerrain) { - StructureTerrain terrain = start.terrain(); - StructureTerrainMode mode = terrain.resolvedMode(); - switch (mode) { - case SOURCE -> integrateSourceTerrain(blocks, area, start, naturalBlock, sourceTerrain); - case PRESERVE, VACUUM -> { - } - case ENCASE -> encasePieces(blocks, area, start, terrain, seed, naturalBlock, palettes); - case BORE, FORCE_CARVE -> carve(blocks, area, start, terrain, seed); - } - } - - private static void carve(FitBlocks blocks, Box area, FitStart start, StructureTerrain terrain, long seed) { - StructureCarveShape shape = terrain.resolvedMode() == StructureTerrainMode.BORE - ? StructureCarveShape.BOX : terrain.resolvedShape(); - if (shape == StructureCarveShape.BOX) { - carvePieceBoxes(blocks, area, start, terrain); - return; - } - carveOrganicColumns(blocks, area, organicCarve( - CarveFootprints.of(start, Math.max(0, terrain.horizontalPadding())), - terrain, shape, carveNoiseIdentity(seed, start))); - } - - static SourceTerrainSnapshot captureSourceTerrain(FitBlocks blocks, Box area, List starts) { - BitSet requiredLayers = new BitSet(area.ySpan()); - boolean requiresSnapshot = false; - for (FitStart start : starts) { - if (requiresSourceTerrainFill(start)) { - requiresSnapshot = true; - markSourceTerrainLayers(area, start, requiredLayers); - } - } - return requiresSnapshot ? SourceTerrainSnapshot.capture(blocks, area, requiredLayers) : null; - } - - private static void markSourceTerrainLayers(Box area, FitStart start, BitSet requiredLayers) { - TerrainAdaptation adaptation = start.adaptation(); - for (FitPiece piece : start.pieces()) { - if (!piece.isRigidOrFixed()) { - continue; - } - Box bounds = piece.box(); - long horizontalDistanceSquared = minimumHorizontalDistanceSquared(area, bounds); - if (adaptation == TerrainAdaptation.BURY) { - long remainingDistanceSquared = (long) SOURCE_BURY_VERTICAL_RADIUS * SOURCE_BURY_VERTICAL_RADIUS - - 1L - horizontalDistanceSquared * 4L; - if (remainingDistanceSquared < 0L) { - continue; - } - int verticalRadius = (int) Math.floor(Math.sqrt(remainingDistanceSquared)); - long groundY = piece.groundY(); - markLayers(area, requiredLayers, groundY - verticalRadius, groundY + verticalRadius); - } else { - long remainingDistanceSquared = (long) SOURCE_ENCAPSULATE_RADIUS * SOURCE_ENCAPSULATE_RADIUS - - 1L - horizontalDistanceSquared; - if (remainingDistanceSquared < 0L) { - continue; - } - int verticalRadius = (int) Math.floor(Math.sqrt(remainingDistanceSquared)); - markLayers(area, requiredLayers, (long) bounds.minY() - verticalRadius, - (long) bounds.maxY() + verticalRadius); - } - } - markSourceJunctionLayers(area, start, requiredLayers); - } - - private static void markSourceJunctionLayers(Box area, FitStart start, BitSet requiredLayers) { - for (BlockPosition anchor : sourceJunctionAnchors(start)) { - long deltaX = intervalDistance(area.minX(), area.maxX(), anchor.x(), anchor.x()); - long deltaZ = intervalDistance(area.minZ(), area.maxZ(), anchor.z(), anchor.z()); - long horizontalDistanceSquared = deltaX * deltaX + deltaZ * deltaZ; - long remainingDistanceSquared = (long) SOURCE_JUNCTION_RADIUS * SOURCE_JUNCTION_RADIUS - - 1L - horizontalDistanceSquared; - if (remainingDistanceSquared < 1L) { - continue; - } - int verticalRadius = (int) Math.floor(Math.sqrt(remainingDistanceSquared)); - markLayers(area, requiredLayers, (long) anchor.y() - verticalRadius, (long) anchor.y() - 1L); - } - } - - private static long minimumHorizontalDistanceSquared(Box area, Box bounds) { - long deltaX = intervalDistance(area.minX(), area.maxX(), bounds.minX(), bounds.maxX()); - long deltaZ = intervalDistance(area.minZ(), area.maxZ(), bounds.minZ(), bounds.maxZ()); - return deltaX * deltaX + deltaZ * deltaZ; - } - - private static long intervalDistance(int firstMin, int firstMax, int secondMin, int secondMax) { - if (firstMax < secondMin) { - return (long) secondMin - firstMax; - } - if (firstMin > secondMax) { - return (long) firstMin - secondMax; - } - return 0L; - } - - private static void markLayers(Box area, BitSet requiredLayers, long minimumY, long maximumY) { - long clippedMinimumY = Math.max(area.minY(), minimumY); - long clippedMaximumY = Math.min(area.maxY(), maximumY); - if (clippedMinimumY > clippedMaximumY) { - return; - } - int fromIndex = Math.toIntExact(clippedMinimumY - area.minY()); - int toIndex = Math.toIntExact(clippedMaximumY - area.minY() + 1L); - requiredLayers.set(fromIndex, toIndex); - } - - /** Whether SOURCE fills terrain for the start: it buries or encapsulates its rigid pieces. */ - private static boolean requiresSourceTerrainFill(FitStart start) { - return start.terrain().resolvedMode() == StructureTerrainMode.SOURCE - && (start.adaptation() == TerrainAdaptation.BURY || start.adaptation() == TerrainAdaptation.ENCAPSULATE); - } - - static boolean clearsLegacyTemplateAir(FitStart start) { - StructureTerrainMode mode = start.terrain().resolvedMode(); - return mode == StructureTerrainMode.ENCASE - || mode == StructureTerrainMode.SOURCE && start.adaptation() != TerrainAdaptation.NONE; - } - - private static void integrateSourceTerrain(FitBlocks blocks, Box area, FitStart start, - IntFunction naturalBlock, SourceTerrainSnapshot sourceTerrain) { - if (start.adaptation() == TerrainAdaptation.BURY) { - fillBuriedTerrain(blocks, area, start, naturalBlock, requireSourceTerrain(blocks, area, start, sourceTerrain)); - } else if (start.adaptation() == TerrainAdaptation.ENCAPSULATE) { - fillEncapsulatedTerrain(blocks, area, start, naturalBlock, - requireSourceTerrain(blocks, area, start, sourceTerrain)); - } - } - - private static SourceTerrainSnapshot requireSourceTerrain(FitBlocks blocks, Box area, FitStart start, - SourceTerrainSnapshot sourceTerrain) { - if (sourceTerrain != null) { - return sourceTerrain; - } - BitSet requiredLayers = new BitSet(area.ySpan()); - markSourceTerrainLayers(area, start, requiredLayers); - return SourceTerrainSnapshot.capture(blocks, area, requiredLayers); - } - - private static void fillBuriedTerrain(FitBlocks blocks, Box area, FitStart start, IntFunction naturalBlock, - SourceTerrainSnapshot sourceTerrain) { - for (FitPiece piece : start.pieces()) { - if (!piece.isRigidOrFixed()) { - continue; - } - Box bounds = piece.box(); - int groundY = piece.groundY(); - int minX = Math.max(area.minX(), bounds.minX() - SOURCE_BURY_HORIZONTAL_RADIUS); - int maxX = Math.min(area.maxX(), bounds.maxX() + SOURCE_BURY_HORIZONTAL_RADIUS); - int minY = Math.max(area.minY(), groundY - SOURCE_BURY_VERTICAL_RADIUS); - int maxY = Math.min(area.maxY(), groundY + SOURCE_BURY_VERTICAL_RADIUS); - int minZ = Math.max(area.minZ(), bounds.minZ() - SOURCE_BURY_HORIZONTAL_RADIUS); - int maxZ = Math.min(area.maxZ(), bounds.maxZ() + SOURCE_BURY_HORIZONTAL_RADIUS); - for (int x = minX; x <= maxX; x++) { - int outX = outset(x, bounds.minX(), bounds.maxX()); - for (int z = minZ; z <= maxZ; z++) { - int outZ = outset(z, bounds.minZ(), bounds.maxZ()); - for (int y = minY; y <= maxY; y++) { - if (insideBurialEnvelope(outX, Math.abs(y - groundY), outZ)) { - fillEncaseable(blocks, x, y, z, naturalBlock, sourceTerrain); - } - } - } - } - } - fillSourceJunctionTerrain(blocks, area, start, naturalBlock, sourceTerrain); - } - - private static void fillEncapsulatedTerrain(FitBlocks blocks, Box area, FitStart start, - IntFunction naturalBlock, SourceTerrainSnapshot sourceTerrain) { - for (FitPiece piece : start.pieces()) { - if (!piece.isRigidOrFixed()) { - continue; - } - Box bounds = piece.box(); - int minX = Math.max(area.minX(), bounds.minX() - SOURCE_ENCAPSULATE_RADIUS); - int maxX = Math.min(area.maxX(), bounds.maxX() + SOURCE_ENCAPSULATE_RADIUS); - int minY = Math.max(area.minY(), bounds.minY() - SOURCE_ENCAPSULATE_RADIUS); - int maxY = Math.min(area.maxY(), bounds.maxY() + SOURCE_ENCAPSULATE_RADIUS); - int minZ = Math.max(area.minZ(), bounds.minZ() - SOURCE_ENCAPSULATE_RADIUS); - int maxZ = Math.min(area.maxZ(), bounds.maxZ() + SOURCE_ENCAPSULATE_RADIUS); - for (int x = minX; x <= maxX; x++) { - int outX = outset(x, bounds.minX(), bounds.maxX()); - for (int z = minZ; z <= maxZ; z++) { - int outZ = outset(z, bounds.minZ(), bounds.maxZ()); - for (int y = minY; y <= maxY; y++) { - if (insideEncapsulationEnvelope(outX, outset(y, bounds.minY(), bounds.maxY()), outZ)) { - fillEncaseable(blocks, x, y, z, naturalBlock, sourceTerrain); - } - } - } - } - } - fillSourceJunctionTerrain(blocks, area, start, naturalBlock, sourceTerrain); - } - - static boolean insideBurialEnvelope(int outX, int verticalDistance, int outZ) { - long horizontalSquared = (long) outX * outX + (long) outZ * outZ; - long verticalSquared = (long) verticalDistance * verticalDistance; - return horizontalSquared * 4L + verticalSquared < (long) SOURCE_BURY_VERTICAL_RADIUS * SOURCE_BURY_VERTICAL_RADIUS; - } - - static boolean insideEncapsulationEnvelope(int outX, int outY, int outZ) { - return (long) outX * outX + (long) outY * outY + (long) outZ * outZ - < (long) SOURCE_ENCAPSULATE_RADIUS * SOURCE_ENCAPSULATE_RADIUS; - } - - static boolean insideSourceJunctionEnvelope(int deltaX, int deltaY, int deltaZ) { - if (deltaY >= 0) { - return false; - } - return (long) deltaX * deltaX + (long) deltaY * deltaY + (long) deltaZ * deltaZ - < (long) SOURCE_JUNCTION_RADIUS * SOURCE_JUNCTION_RADIUS; - } - - private static void fillSourceJunctionTerrain(FitBlocks blocks, Box area, FitStart start, - IntFunction naturalBlock, SourceTerrainSnapshot sourceTerrain) { - for (BlockPosition anchor : sourceJunctionAnchors(start)) { - int minX = Math.max(area.minX(), anchor.x() - SOURCE_JUNCTION_RADIUS + 1); - int maxX = Math.min(area.maxX(), anchor.x() + SOURCE_JUNCTION_RADIUS - 1); - int minY = Math.max(area.minY(), anchor.y() - SOURCE_JUNCTION_RADIUS + 1); - int maxY = Math.min(area.maxY(), anchor.y() - 1); - int minZ = Math.max(area.minZ(), anchor.z() - SOURCE_JUNCTION_RADIUS + 1); - int maxZ = Math.min(area.maxZ(), anchor.z() + SOURCE_JUNCTION_RADIUS - 1); - for (int x = minX; x <= maxX; x++) { - int deltaX = x - anchor.x(); - for (int z = minZ; z <= maxZ; z++) { - int deltaZ = z - anchor.z(); - for (int y = minY; y <= maxY; y++) { - if (insideSourceJunctionEnvelope(deltaX, y - anchor.y(), deltaZ)) { - fillEncaseable(blocks, x, y, z, naturalBlock, sourceTerrain); - } - } - } - } - } - } - - /** The jigsaw junctions of every piece, each place once. The order is a set's, as no fill depends on it. */ - private static Set sourceJunctionAnchors(FitStart start) { - Set anchors = new HashSet<>(); - for (FitPiece piece : start.pieces()) { - anchors.addAll(piece.junctions()); - } - return anchors; - } - - private static int outset(int value, int minimum, int maximum) { - if (value < minimum) { - return minimum - value; - } - return Math.max(0, value - maximum); - } - - private static void fillEncaseable(FitBlocks blocks, int x, int y, int z, IntFunction naturalBlock, - SourceTerrainSnapshot sourceTerrain) { - if (blocks.isEncaseable(blocks.get(x, y, z))) { - blocks.set(x, y, z, sourceEncaseBlock(x, y, z, naturalBlock, sourceTerrain)); - } - } - - /** The nearest natural terrain block of the snapshot along the axes, within 8 blocks; else the dimension's own. */ - static BlockState sourceEncaseBlock(int x, int y, int z, IntFunction naturalBlock, - SourceTerrainSnapshot sourceTerrain) { - for (int distance = 1; distance <= SOURCE_MATERIAL_SAMPLE_RADIUS; distance++) { - BlockState sampled = sourceTerrain.stateAt(x - distance, y, z); - if (sampled != null) { - return sampled; - } - sampled = sourceTerrain.stateAt(x + distance, y, z); - if (sampled != null) { - return sampled; - } - sampled = sourceTerrain.stateAt(x, y, z - distance); - if (sampled != null) { - return sampled; - } - sampled = sourceTerrain.stateAt(x, y, z + distance); - if (sampled != null) { - return sampled; - } - } - return naturalBlock.apply(y); - } - - private static BlockState sourceTerrainBlock(FitBlocks blocks, BlockState state) { - if (!blocks.isSolid(state) || blocks.isTree(state)) { - return null; - } - if (VANILLA_SOURCE_TERRAIN_BLOCKS.contains(state.material().toString())) { - return state; - } - for (ResourceId tag : SOURCE_TERRAIN_TAGS) { - if (blocks.inTag(state, tag)) { - return state; - } - } - return null; - } - - static OrganicCarve organicCarve(StructureCarvingFootprint footprint, StructureTerrain terrain, - StructureCarveShape shape, long identity) { - double strength = terrain.resolvedErosionStrength(); - double lobeStrength = terrain.resolvedLobeStrength(); - RNG noiseRng = new RNG(identity); - CNG blob = null; - CNG ceilingRoll = null; - CNG floorRoll = null; - CNG lobe = null; - if (shape == StructureCarveShape.ERODED && strength > 0D) { - blob = CNG.signature(noiseRng); - ceilingRoll = CNG.signature(noiseRng.nextParallelRNG(CARVE_CEILING_ROLL_SIGNATURE)); - floorRoll = CNG.signature(noiseRng.nextParallelRNG(CARVE_FLOOR_ROLL_SIGNATURE)); - } - if (shape == StructureCarveShape.ERODED && lobeStrength > 0D) { - // A plain single octave channel: the fractured signature noise has no usable low frequency band. - lobe = new CNG(noiseRng.nextParallelRNG(CARVE_LOBE_SIGNATURE), 1D, 1); - } - return new OrganicCarve(footprint, shape, - Math.max(0, terrain.horizontalPadding()), - Math.max(0, terrain.ceilingPadding()), - Math.max(0, terrain.floorPadding()), - strength, terrain.resolvedErosionFrequency(), blob, ceilingRoll, floorRoll, - lobe, terrain.resolvedLobeFrequency(), lobeStrength); - } - - static void carveOrganicColumns(FitBlocks blocks, Box area, OrganicCarve carve) { - StructureCarvingFootprint footprint = carve.footprint(); - int minX = Math.max(area.minX(), footprint.minX()); - int maxX = Math.min(area.maxX(), footprint.maxX()); - int minZ = Math.max(area.minZ(), footprint.minZ()); - int maxZ = Math.min(area.maxZ(), footprint.maxZ()); - if (minX > maxX || minZ > maxZ) { - return; - } - boolean eroded = carve.blob() != null; - for (int z = minZ; z <= maxZ; z++) { - for (int x = minX; x <= maxX; x++) { - int index = footprint.indexAt(x, z); - long horizontalDistanceSquared = footprint.distanceSquaredAt(index); - double sideReach = StructureCarveEnvelope.lobedSideReach(carve.lobe(), - carve.lobeFrequency(), carve.lobeStrength(), x, z, carve.horizontalPadding()); - double sideReachSquared = sideReach * sideReach; - if (horizontalDistanceSquared > sideReachSquared) { - continue; - } - double normalizedHorizontal = sideReachSquared == 0D ? 0D : horizontalDistanceSquared / sideReachSquared; - int sourceMinY = footprint.sourceMinYAt(index); - int sourceMaxY = footprint.sourceMaxYAt(index); - double upReach = eroded - ? StructureCarveEnvelope.lobedUpReach(carve.lobe(), carve.lobeFrequency(), - carve.lobeStrength(), x, z, - StructureCarveEnvelope.erodedUpReach(carve.ceilingRoll(), - carve.frequency(), carve.strength(), x, z, carve.ceilingPadding())) - : Math.max(1D, carve.ceilingPadding()); - double floorReach = eroded - ? StructureCarveEnvelope.erodedDownReach(carve.floorRoll(), carve.frequency(), - carve.strength(), x, z, carve.floorPadding()) - : carve.floorPadding(); - int columnMinY = Math.max(area.minY(), sourceMinY - (int) Math.floor(floorReach)); - int columnMaxY = Math.min(area.maxY(), - sourceMaxY + (eroded ? (int) Math.ceil(upReach) : carve.ceilingPadding())); - double downReach = Math.max(1D, floorReach); - for (int y = columnMinY; y <= columnMaxY; y++) { - double normalizedVertical = StructureCarveEnvelope.normalizedVerticalDistance( - y, sourceMinY, sourceMaxY, upReach, downReach); - double distanceSquared = normalizedHorizontal + normalizedVertical * normalizedVertical; - if (distanceSquared > 1D) { - continue; - } - if (distanceSquared > 0D && eroded) { - double noise = carve.blob().fitDouble(0D, 1D, - x * carve.frequency(), y * carve.frequency(), z * carve.frequency()); - if (!StructureCarveEnvelope.shouldCarveOverboreCell( - carve.shape(), distanceSquared, noise, carve.strength())) { - continue; - } - } - blocks.set(x, y, z, FitBlocks.AIR); - } - } - } - } - - private static long carveNoiseIdentity(long seed, FitStart start) { - return seed - ^ ((long) start.chunkX() * CARVE_IDENTITY_X) - ^ ((long) start.chunkZ() * CARVE_IDENTITY_Z) - ^ start.structureId().hashCode(); - } - - private static void encasePieces(FitBlocks blocks, Box area, FitStart start, StructureTerrain terrain, long seed, - IntFunction naturalBlock, FitPalettes palettes) { - Optional palette = terrain.encasePalette(); - long paletteSeed = seed ^ start.structureId().hashCode(); - for (FitPiece piece : start.pieces()) { - Box shell = paddedPieceArea(area, piece.box(), terrain); - if (shell == null) { - continue; - } - for (int x = shell.minX(); x <= shell.maxX(); x++) { - for (int z = shell.minZ(); z <= shell.maxZ(); z++) { - for (int y = shell.minY(); y <= shell.maxY(); y++) { - if (!blocks.isEncaseable(blocks.get(x, y, z))) { - continue; - } - BlockState fill = palette.isEmpty() - ? naturalBlock.apply(y) - : Objects.requireNonNull(palettes.at(palette.get(), paletteSeed, x, y, z), - "Encase palette returned no block for " + start.structureId() + " at " - + x + "," + y + "," + z); - blocks.set(x, y, z, fill); - } - } - } - } - } - - private static void carvePieceBoxes(FitBlocks blocks, Box area, FitStart start, StructureTerrain terrain) { - for (FitPiece piece : start.pieces()) { - Box carve = paddedPieceArea(area, piece.box(), terrain); - if (carve == null) { - continue; - } - for (int x = carve.minX(); x <= carve.maxX(); x++) { - for (int z = carve.minZ(); z <= carve.maxZ(); z++) { - for (int y = carve.minY(); y <= carve.maxY(); y++) { - blocks.set(x, y, z, FitBlocks.AIR); - } - } - } - } - } - - private static Box paddedPieceArea(Box area, Box bounds, StructureTerrain terrain) { - int horizontalPadding = Math.max(0, terrain.horizontalPadding()); - int minX = Math.max(area.minX(), bounds.minX() - horizontalPadding); - int minY = Math.max(area.minY(), bounds.minY() - Math.max(0, terrain.floorPadding())); - int minZ = Math.max(area.minZ(), bounds.minZ() - horizontalPadding); - int maxX = Math.min(area.maxX(), bounds.maxX() + horizontalPadding); - int maxY = Math.min(area.maxY(), bounds.maxY() + Math.max(0, terrain.ceilingPadding())); - int maxZ = Math.min(area.maxZ(), bounds.maxZ() + horizontalPadding); - if (minX > maxX || minY > maxY || minZ > maxZ) { - return null; - } - return new Box(minX, minY, minZ, maxX, maxY, maxZ); - } - - /** Clears the air of rigid legacy templates over the terrain, from their ground level up, sparing trees. */ - static void clearLegacyTemplateAir(FitBlocks blocks, Box area, FitStart start) { - for (FitPiece piece : start.pieces()) { - if (!piece.isRigid() || !piece.box().intersects(area)) { - continue; - } - int groundY = piece.groundY(); - for (BlockPosition air : piece.legacyAir(area)) { - BlockState existing = blocks.get(air.x(), air.y(), air.z()); - if (shouldClearLegacyAir(air.y(), groundY, blocks.isAir(existing)) && !blocks.isTree(existing)) { - blocks.set(air.x(), air.y(), air.z(), FitBlocks.AIR); - } - } - } - } - - static boolean shouldClearLegacyAir(int airY, int groundY, boolean existingAir) { - return airY >= groundY && !existingAir; - } - - /** The natural terrain blocks of some layers of the area, read before any fill, so fills never feed on fills. */ - static final class SourceTerrainSnapshot { - private final Box area; - private final int width; - private final BlockState[][] statesByLayer; - private final int sampledCells; - - private SourceTerrainSnapshot(Box area, int width, BlockState[][] statesByLayer, int sampledCells) { - this.area = area; - this.width = width; - this.statesByLayer = statesByLayer; - this.sampledCells = sampledCells; - } - - static SourceTerrainSnapshot capture(FitBlocks blocks, Box area, BitSet requiredLayers) { - Objects.requireNonNull(requiredLayers, "Source terrain snapshot requires sampled layers"); - int width = area.xSpan(); - int horizontalCells = Math.multiplyExact(width, area.zSpan()); - int height = area.ySpan(); - BlockState[][] statesByLayer = new BlockState[height][]; - int sampledCells = 0; - for (int layer = requiredLayers.nextSetBit(0); layer >= 0; layer = requiredLayers.nextSetBit(layer + 1)) { - if (layer >= height) { - throw new IllegalArgumentException("Source terrain snapshot layer exceeds writable bounds: " + layer); - } - BlockState[] states = new BlockState[horizontalCells]; - statesByLayer[layer] = states; - sampledCells = Math.addExact(sampledCells, horizontalCells); - int y = Math.addExact(area.minY(), layer); - for (int z = area.minZ(); z <= area.maxZ(); z++) { - for (int x = area.minX(); x <= area.maxX(); x++) { - states[area.columnIndex(x, z)] = sourceTerrainBlock(blocks, blocks.get(x, y, z)); - } - } - } - return new SourceTerrainSnapshot(area, width, statesByLayer, sampledCells); - } - - BlockState stateAt(int x, int y, int z) { - if (!area.contains(x, y, z)) { - return null; - } - BlockState[] states = statesByLayer[y - area.minY()]; - if (states == null) { - return null; - } - return states[(z - area.minZ()) * width + x - area.minX()]; - } - - int sampledCells() { - return sampledCells; - } - } - - record OrganicCarve(StructureCarvingFootprint footprint, StructureCarveShape shape, - int horizontalPadding, int ceilingPadding, int floorPadding, - double strength, double frequency, CNG blob, CNG ceilingRoll, CNG floorRoll, - CNG lobe, double lobeFrequency, double lobeStrength) { - } -} diff --git a/src/main/java/art/arcane/iris/engine/image/CompiledIrisImageMap.java b/src/main/java/art/arcane/iris/engine/image/CompiledIrisImageMap.java deleted file mode 100644 index 3fdf34378..000000000 --- a/src/main/java/art/arcane/iris/engine/image/CompiledIrisImageMap.java +++ /dev/null @@ -1,424 +0,0 @@ -package art.arcane.iris.engine.image; - -import art.arcane.iris.engine.object.image.IrisImage; -import art.arcane.iris.engine.object.image.IrisImageMap; -import art.arcane.iris.engine.object.image.IrisImageMapOutOfBounds; -import art.arcane.iris.engine.object.image.IrisImageMapSampling; -import art.arcane.iris.engine.object.image.IrisImageMapType; - -import java.util.Objects; - -public final class CompiledIrisImageMap { - private final State state; - - CompiledIrisImageMap(State state) { - this.state = Objects.requireNonNull(state, "Compiled image-map state"); - } - - public static CompiledIrisImageMap compile(IrisImageMap definition, IrisImage image) { - return IrisImageMapCompiler.compile(definition, image); - } - - public IrisImageMap getDefinition() { - return state.definition(); - } - - public IrisImageMapSourceMetadata getSourceMetadata() { - return state.sourceMetadata(); - } - - public IrisImageMapType getType() { - return state.type(); - } - - public int getSourceWidth() { - return state.sourceMetadata().width(); - } - - public int getSourceHeight() { - return state.sourceMetadata().height(); - } - - public String getContentHash() { - return state.contentHash(); - } - - public String contentHash() { - return state.contentHash(); - } - - public CompiledIrisImageMap withoutDecodedValues() { - return state.scalarValues() == null && state.targetIndices() == null - ? this - : new CompiledIrisImageMap(state.withoutDecodedValues()); - } - - public int getClippedPixelCount() { - return state.clippedPixelCount(); - } - - public int getUnknownColorPixelCount() { - return state.unknownColorPixelCount(); - } - - public boolean containsWorld(double worldX, double worldZ) { - if (!Double.isFinite(worldX) || !Double.isFinite(worldZ)) { - return false; - } - double sourceX = state.sourceTransform().sourceX(worldX, worldZ); - double sourceZ = state.sourceTransform().sourceZ(worldX, worldZ); - return validSourceCoordinate(sourceX, sourceZ) - && sourceX >= 0D - && sourceZ >= 0D - && sourceX < state.sourceMetadata().width() - && sourceZ < state.sourceMetadata().height(); - } - - public boolean containsWorldForSampling(double worldX, double worldZ) { - if (!Double.isFinite(worldX) || !Double.isFinite(worldZ)) { - return false; - } - double sourceX = state.sourceTransform().sourceX(worldX, worldZ); - double sourceZ = state.sourceTransform().sourceZ(worldX, worldZ); - if (!validSourceCoordinate(sourceX, sourceZ)) { - return false; - } - long baseX = floorToLong(sourceX); - long baseZ = floorToLong(sourceZ); - return switch (state.sampling()) { - case NEAREST -> sourceIndexInBounds(baseX, baseZ); - case BILINEAR -> bilinearKernelInBounds(sourceX, sourceZ, baseX, baseZ); - case BICUBIC -> bicubicKernelInBounds(sourceX, sourceZ, baseX, baseZ); - }; - } - - public double sampleNormalized(double worldX, double worldZ) { - requireScalarType(); - requireWorldCoordinate(worldX, worldZ); - double sourceX = state.sourceTransform().sourceX(worldX, worldZ); - double sourceZ = state.sourceTransform().sourceZ(worldX, worldZ); - requireSourceCoordinate(sourceX, sourceZ); - double sampled = switch (state.sampling()) { - case NEAREST -> scalarAt(floorToLong(sourceX), floorToLong(sourceZ)); - case BILINEAR -> bilinear(sourceX, sourceZ); - case BICUBIC -> bicubic(sourceX, sourceZ); - }; - return clamp01(sampled); - } - - public double sampleHeight(double worldX, double worldZ) { - if (!isHeightType()) { - throw new IrisImageMapValidationException("Image map type " + state.type() + " does not produce terrain heights"); - } - double normalized = sampleNormalized(worldX, worldZ); - double height = state.minimumHeight() - + (normalized * (state.maximumHeight() - state.minimumHeight())) - + state.verticalOffset(); - if (!state.clampHeight()) { - return height; - } - return Math.max(state.minimumHeight(), Math.min(state.maximumHeight(), height)); - } - - public String sampleTarget(double worldX, double worldZ) { - if (state.type() != IrisImageMapType.COLOR_MAP) { - throw new IrisImageMapValidationException("Image map type " + state.type() + " does not produce legend targets"); - } - if (state.targetIndices() == null) { - throw new IrisImageMapValidationException("Compiled image-map view does not retain decoded target data"); - } - requireWorldCoordinate(worldX, worldZ); - double transformedX = state.sourceTransform().sourceX(worldX, worldZ); - double transformedZ = state.sourceTransform().sourceZ(worldX, worldZ); - requireSourceCoordinate(transformedX, transformedZ); - long sourceX = floorToLong(transformedX); - long sourceZ = floorToLong(transformedZ); - int resolvedX = resolveIndex(sourceX, state.sourceMetadata().width()); - int resolvedZ = resolveIndex(sourceZ, state.sourceMetadata().height()); - if (resolvedX < 0 || resolvedZ < 0) { - return state.fallbackTarget(); - } - int targetIndex = state.targetIndices().get((resolvedZ * state.sourceMetadata().width()) + resolvedX); - return targetIndex < 0 ? null : state.targets()[targetIndex]; - } - - private void requireWorldCoordinate(double worldX, double worldZ) { - if (!Double.isFinite(worldX) || !Double.isFinite(worldZ)) { - throw new IrisImageMapValidationException("World coordinates must be finite, got " + worldX + "," + worldZ); - } - } - - private void requireSourceCoordinate(double sourceX, double sourceZ) { - if (!validSourceCoordinate(sourceX, sourceZ)) { - throw new IrisImageMapValidationException( - "World coordinates transform outside the supported source-coordinate range: " - + sourceX + "," + sourceZ - ); - } - } - - private boolean bilinearKernelInBounds(double sourceX, double sourceZ, long baseX, long baseZ) { - long maximumX = sourceX == baseX ? baseX : baseX + 1L; - long maximumZ = sourceZ == baseZ ? baseZ : baseZ + 1L; - return baseX >= 0L - && baseZ >= 0L - && maximumX < state.sourceMetadata().width() - && maximumZ < state.sourceMetadata().height(); - } - - private boolean bicubicKernelInBounds(double sourceX, double sourceZ, long baseX, long baseZ) { - if (sourceX == baseX && sourceZ == baseZ) { - return sourceIndexInBounds(baseX, baseZ); - } - return baseX >= 1L - && baseZ >= 1L - && baseX + 2L < state.sourceMetadata().width() - && baseZ + 2L < state.sourceMetadata().height(); - } - - private boolean sourceIndexInBounds(long sourceX, long sourceZ) { - return sourceX >= 0L - && sourceZ >= 0L - && sourceX < state.sourceMetadata().width() - && sourceZ < state.sourceMetadata().height(); - } - - private double bilinear(double sourceX, double sourceZ) { - long x0 = floorToLong(sourceX); - long z0 = floorToLong(sourceZ); - double fractionX = sourceX - x0; - double fractionZ = sourceZ - z0; - if (fractionX == 0D && fractionZ == 0D) { - return scalarAt(x0, z0); - } - if (fractionZ == 0D) { - return lerp(scalarAt(x0, z0), scalarAt(x0 + 1L, z0), fractionX); - } - if (fractionX == 0D) { - return lerp(scalarAt(x0, z0), scalarAt(x0, z0 + 1L), fractionZ); - } - double top = lerp(scalarAt(x0, z0), scalarAt(x0 + 1L, z0), fractionX); - double bottom = lerp(scalarAt(x0, z0 + 1L), scalarAt(x0 + 1L, z0 + 1L), fractionX); - return lerp(top, bottom, fractionZ); - } - - private double bicubic(double sourceX, double sourceZ) { - long baseX = floorToLong(sourceX); - long baseZ = floorToLong(sourceZ); - double fractionX = sourceX - baseX; - double fractionZ = sourceZ - baseZ; - if (fractionX == 0D && fractionZ == 0D) { - return scalarAt(baseX, baseZ); - } - double row0 = cubicRow(baseX, baseZ - 1L, fractionX); - double row1 = cubicRow(baseX, baseZ, fractionX); - double row2 = cubicRow(baseX, baseZ + 1L, fractionX); - double row3 = cubicRow(baseX, baseZ + 2L, fractionX); - return cubic(row0, row1, row2, row3, fractionZ); - } - - private double cubicRow(long baseX, long sourceZ, double fractionX) { - return cubic( - scalarAt(baseX - 1L, sourceZ), - scalarAt(baseX, sourceZ), - scalarAt(baseX + 1L, sourceZ), - scalarAt(baseX + 2L, sourceZ), - fractionX - ); - } - - private double scalarAt(long sourceX, long sourceZ) { - int resolvedX = resolveIndex(sourceX, state.sourceMetadata().width()); - int resolvedZ = resolveIndex(sourceZ, state.sourceMetadata().height()); - if (resolvedX < 0 || resolvedZ < 0) { - return state.fallbackValue(); - } - return state.scalarValues().get((resolvedZ * state.sourceMetadata().width()) + resolvedX); - } - - private int resolveIndex(long coordinate, int length) { - if (coordinate >= 0L && coordinate < length) { - return (int) coordinate; - } - IrisImageMapOutOfBounds outOfBounds = state.outOfBounds(); - return switch (outOfBounds) { - case FALLBACK -> -1; - case CLAMP -> coordinate < 0L ? 0 : length - 1; - case REPEAT -> (int) Math.floorMod(coordinate, (long) length); - case MIRROR -> mirrorIndex(coordinate, length); - case ERROR -> throw new IrisImageMapValidationException( - "Source coordinate " + coordinate + " is outside 0.." + (length - 1) - ); - }; - } - - private int mirrorIndex(long coordinate, int length) { - if (length == 1) { - return 0; - } - long period = (long) length * 2L; - long mirrored = Math.floorMod(coordinate, period); - if (mirrored >= length) { - mirrored = period - 1L - mirrored; - } - return (int) mirrored; - } - - private boolean isHeightType() { - return state.type() == IrisImageMapType.GRAYSCALE_HEIGHT - || state.type() == IrisImageMapType.RGB_HEIGHT; - } - - private void requireScalarType() { - if (state.scalarValues() == null) { - if (isHeightType() - || state.type() == IrisImageMapType.BINARY_MASK - || state.type() == IrisImageMapType.GRAYSCALE_MASK - || state.type() == IrisImageMapType.ALPHA_MASK) { - throw new IrisImageMapValidationException("Compiled image-map view does not retain decoded scalar data"); - } - throw new IrisImageMapValidationException("Image map type " + state.type() + " does not produce normalized scalar data"); - } - } - - private static long floorToLong(double value) { - return (long) Math.floor(value); - } - - private static boolean validSourceCoordinate(double sourceX, double sourceZ) { - double safeMinimum = -9_000_000_000_000_000_000D; - double safeMaximum = 9_000_000_000_000_000_000D; - return Double.isFinite(sourceX) - && Double.isFinite(sourceZ) - && sourceX >= safeMinimum - && sourceX <= safeMaximum - && sourceZ >= safeMinimum - && sourceZ <= safeMaximum; - } - - private static double lerp(double a, double b, double factor) { - return a + ((b - a) * factor); - } - - private static double cubic(double p0, double p1, double p2, double p3, double factor) { - double squared = factor * factor; - double cubed = squared * factor; - return 0.5D * ((2D * p1) - + ((-p0 + p2) * factor) - + (((2D * p0) - (5D * p1) + (4D * p2) - p3) * squared) - + ((-p0 + (3D * p1) - (3D * p2) + p3) * cubed)); - } - - private static double clamp01(double value) { - return Math.max(0D, Math.min(1D, value)); - } - - static record State( - IrisImageMap definition, - IrisImageMapSourceMetadata sourceMetadata, - IrisImageMapType type, - FloatTiles scalarValues, - IntTiles targetIndices, - String[] targets, - SourceTransform sourceTransform, - IrisImageMapSampling sampling, - IrisImageMapOutOfBounds outOfBounds, - double fallbackValue, - String fallbackTarget, - double minimumHeight, - double maximumHeight, - double verticalOffset, - boolean clampHeight, - int clippedPixelCount, - int unknownColorPixelCount, - String contentHash - ) { - State withoutDecodedValues() { - return new State( - definition, - sourceMetadata, - type, - null, - null, - null, - sourceTransform, - sampling, - outOfBounds, - fallbackValue, - fallbackTarget, - minimumHeight, - maximumHeight, - verticalOffset, - clampHeight, - clippedPixelCount, - unknownColorPixelCount, - contentHash - ); - } - } - - static record SourceTransform( - double sourceXFromWorldX, - double sourceXFromWorldZ, - double sourceXOffset, - double sourceZFromWorldX, - double sourceZFromWorldZ, - double sourceZOffset - ) { - double sourceX(double worldX, double worldZ) { - return (sourceXFromWorldX * worldX) + (sourceXFromWorldZ * worldZ) + sourceXOffset; - } - - double sourceZ(double worldX, double worldZ) { - return (sourceZFromWorldX * worldX) + (sourceZFromWorldZ * worldZ) + sourceZOffset; - } - } - - static final class FloatTiles { - private static final int TILE_SHIFT = 20; - private static final int TILE_SIZE = 1 << TILE_SHIFT; - private static final int TILE_MASK = TILE_SIZE - 1; - private final float[][] tiles; - - FloatTiles(int size) { - int tileCount = (size + TILE_SIZE - 1) >>> TILE_SHIFT; - tiles = new float[tileCount][]; - for (int tile = 0; tile < tileCount; tile++) { - int remaining = size - (tile << TILE_SHIFT); - tiles[tile] = new float[Math.min(TILE_SIZE, remaining)]; - } - } - - float get(int index) { - return tiles[index >>> TILE_SHIFT][index & TILE_MASK]; - } - - void set(int index, float value) { - tiles[index >>> TILE_SHIFT][index & TILE_MASK] = value; - } - } - - static final class IntTiles { - private static final int TILE_SHIFT = 20; - private static final int TILE_SIZE = 1 << TILE_SHIFT; - private static final int TILE_MASK = TILE_SIZE - 1; - private final int[][] tiles; - - IntTiles(int size) { - int tileCount = (size + TILE_SIZE - 1) >>> TILE_SHIFT; - tiles = new int[tileCount][]; - for (int tile = 0; tile < tileCount; tile++) { - int remaining = size - (tile << TILE_SHIFT); - tiles[tile] = new int[Math.min(TILE_SIZE, remaining)]; - } - } - - int get(int index) { - return tiles[index >>> TILE_SHIFT][index & TILE_MASK]; - } - - void set(int index, int value) { - tiles[index >>> TILE_SHIFT][index & TILE_MASK] = value; - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/image/IrisImageMapCompiler.java b/src/main/java/art/arcane/iris/engine/image/IrisImageMapCompiler.java deleted file mode 100644 index 9d942878a..000000000 --- a/src/main/java/art/arcane/iris/engine/image/IrisImageMapCompiler.java +++ /dev/null @@ -1,825 +0,0 @@ -package art.arcane.iris.engine.image; - -import art.arcane.iris.engine.object.image.IrisImage; -import art.arcane.iris.engine.object.image.IrisImageColorMode; -import art.arcane.iris.engine.object.image.IrisImageMap; -import art.arcane.iris.engine.object.image.IrisImageMapAlpha; -import art.arcane.iris.engine.object.image.IrisImageMapOrigin; -import art.arcane.iris.engine.object.image.IrisImageMapOutOfBounds; -import art.arcane.iris.engine.object.image.IrisImageMapSampling; -import art.arcane.iris.engine.object.image.IrisImageMapType; -import art.arcane.iris.engine.object.image.IrisImageMapUnknownColor; -import art.arcane.volmlib.util.collection.KMap; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HexFormat; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.regex.Pattern; - -public final class IrisImageMapCompiler { - public static final int MINIMUM_DIMENSION = 1; - public static final int MAXIMUM_DIMENSION = 16_384; - public static final long MAXIMUM_PIXELS = 16_777_216L; - - private static final Pattern COLOR_PATTERN = Pattern.compile("#[0-9a-fA-F]{6}"); - - private IrisImageMapCompiler() { - } - - public static CompiledIrisImageMap compile(IrisImageMap definition, IrisImage image) { - if (definition == null) { - throw new IrisImageMapValidationException("Image-map definition is required"); - } - if (image == null) { - throw new IrisImageMapValidationException("Decoded image source is required"); - } - - List diagnostics = validate(definition, image); - if (!diagnostics.isEmpty()) { - throw new IrisImageMapValidationException(diagnostics); - } - - try { - SourceDigest sourceDigest = hashSource(image); - IrisImageMapSourceMetadata metadata = new IrisImageMapSourceMetadata( - image.getFormat(), - image.getColorMode(), - image.getWidth(), - image.getHeight(), - image.getColorComponentCount(), - image.getChannelCount(), - image.getBitDepth(), - image.hasAlpha(), - sourceDigest.minimumAlpha(), - sourceDigest.maximumAlpha(), - sourceDigest.hash() - ); - IrisImageMap snapshot = snapshot(definition); - CompiledIrisImageMap.FloatTiles scalarValues = null; - CompiledIrisImageMap.IntTiles targetIndices = null; - String[] targets = null; - int clippedPixelCount = 0; - int unknownColorPixelCount = 0; - - if (definition.getType() == IrisImageMapType.COLOR_MAP) { - CompiledTargets compiledTargets = compileTargets(definition, image); - targetIndices = compiledTargets.indices(); - targets = compiledTargets.targets(); - unknownColorPixelCount = compiledTargets.unknownColorPixelCount(); - } else { - scalarValues = compileScalars(definition, image); - if (definition.getSmoothingRadius() > 0) { - smooth(scalarValues, image.getWidth(), image.getHeight(), definition.getSmoothingRadius()); - } - clippedPixelCount = countClippedPixels( - definition, scalarValues, Math.multiplyExact(image.getWidth(), image.getHeight()) - ); - } - - String contentHash = hashContent(snapshot, metadata); - String fallbackTarget = definition.getFallbackTarget() == null || definition.getFallbackTarget().isBlank() - ? null - : definition.getFallbackTarget(); - CompiledIrisImageMap.SourceTransform sourceTransform = compileSourceTransform(definition); - CompiledIrisImageMap.State state = new CompiledIrisImageMap.State( - snapshot, - metadata, - definition.getType(), - scalarValues, - targetIndices, - targets, - sourceTransform, - definition.getSampling(), - definition.getOutOfBounds(), - definition.getFallbackValue(), - fallbackTarget, - definition.getMinimumHeight(), - definition.getMaximumHeight(), - definition.getVerticalOffset(), - definition.isClamp(), - clippedPixelCount, - unknownColorPixelCount, - contentHash - ); - return new CompiledIrisImageMap(state); - } catch (IrisImageMapValidationException exception) { - throw exception; - } catch (RuntimeException exception) { - throw new IrisImageMapValidationException( - "Failed to compile image map '" + definition.getSource() + "': " + exception.getMessage(), - exception - ); - } - } - - private static List validate(IrisImageMap definition, IrisImage image) { - List diagnostics = new ArrayList<>(); - if (definition.getSource() == null || definition.getSource().isBlank()) { - diagnostics.add("Image-map source must not be blank"); - } - validateSource(image, diagnostics); - validateCoordinates(definition, diagnostics); - validateScalarSettings(definition, diagnostics); - validateType(definition, image, diagnostics); - validateLegend(definition, diagnostics); - return diagnostics; - } - - private static void validateSource(IrisImage image, List diagnostics) { - if (!"png".equals(image.getFormat())) { - diagnostics.add("Image format must be PNG, got " + image.getFormat()); - } - int width = image.getWidth(); - int height = image.getHeight(); - if (width < MINIMUM_DIMENSION || width > MAXIMUM_DIMENSION) { - diagnostics.add("Image width must be " + MINIMUM_DIMENSION + ".." + MAXIMUM_DIMENSION + ", got " + width); - } - if (height < MINIMUM_DIMENSION || height > MAXIMUM_DIMENSION) { - diagnostics.add("Image height must be " + MINIMUM_DIMENSION + ".." + MAXIMUM_DIMENSION + ", got " + height); - } - long pixels = (long) width * height; - if (pixels > MAXIMUM_PIXELS) { - diagnostics.add("Image contains " + pixels + " pixels; maximum is " + MAXIMUM_PIXELS); - } - if (image.getColorMode() == IrisImageColorMode.INDEXED) { - diagnostics.add("Indexed PNG images are unsupported; convert the source to grayscale, RGB, or RGBA"); - } else if (image.getColorMode() == IrisImageColorMode.UNSUPPORTED) { - diagnostics.add("Unsupported PNG color mode with " + image.getColorComponentCount() - + " color components and " + image.getChannelCount() + " channels"); - } - } - - private static void validateCoordinates(IrisImageMap definition, List diagnostics) { - if (!finiteAtLeast(definition.getBlocksPerPixel(), IrisImageMap.MINIMUM_SCALE)) { - diagnostics.add("blocksPerPixel must be finite and at least " + IrisImageMap.MINIMUM_SCALE); - } - IrisImageMapOrigin origin = definition.getOrigin(); - if (origin == null || !Double.isFinite(origin.getX()) || !Double.isFinite(origin.getZ())) { - diagnostics.add("origin X and Z must be finite"); - } - IrisImageMapOrigin sourceOrigin = definition.getSourceOrigin(); - if (sourceOrigin == null || !Double.isFinite(sourceOrigin.getX()) || !Double.isFinite(sourceOrigin.getZ())) { - diagnostics.add("sourceOrigin X and Z must be finite"); - } - if (definition.getRotation() == null) { - diagnostics.add("rotation is required"); - } - if (definition.getSampling() == null) { - diagnostics.add("sampling is required"); - } - if (definition.getOutOfBounds() == null) { - diagnostics.add("outOfBounds is required"); - } - } - - private static void validateScalarSettings(IrisImageMap definition, List diagnostics) { - if (!range(definition.getFallbackValue(), 0D, 1D)) { - diagnostics.add("fallbackValue must be finite and within 0..1"); - } - if (!Double.isFinite(definition.getMinimumHeight()) || !Double.isFinite(definition.getMaximumHeight())) { - diagnostics.add("minimumHeight and maximumHeight must be finite"); - } else if (definition.getMaximumHeight() < definition.getMinimumHeight()) { - diagnostics.add("maximumHeight must be greater than or equal to minimumHeight"); - } - if (!Double.isFinite(definition.getVerticalOffset())) { - diagnostics.add("verticalOffset must be finite"); - } - if (!finiteAtLeast(definition.getCurveExponent(), IrisImageMap.MINIMUM_SCALE)) { - diagnostics.add("curveExponent must be finite and at least " + IrisImageMap.MINIMUM_SCALE); - } - if (definition.getSmoothingRadius() < 0 || definition.getSmoothingRadius() > 32) { - diagnostics.add("smoothingRadius must be within 0..32"); - } - if (!range(definition.getThreshold(), 0D, 1D)) { - diagnostics.add("threshold must be finite and within 0..1"); - } - if (!range(definition.getFalloff(), 0D, 1D)) { - diagnostics.add("falloff must be finite and within 0..1"); - } - if (!range(definition.getColorTolerance(), 0D, IrisImageMap.MAXIMUM_COLOR_TOLERANCE)) { - diagnostics.add("colorTolerance must be finite and within 0.." - + IrisImageMap.MAXIMUM_COLOR_TOLERANCE); - } - if (definition.getAlpha() == null) { - diagnostics.add("alpha policy is required"); - } - if (definition.getUnknownColor() == null) { - diagnostics.add("unknownColor policy is required"); - } - } - - private static void validateType(IrisImageMap definition, IrisImage image, List diagnostics) { - IrisImageMapType type = definition.getType(); - if (type == null) { - diagnostics.add("Image-map type is required"); - return; - } - - IrisImageColorMode colorMode = image.getColorMode(); - int bitDepth = image.getBitDepth(); - switch (type) { - case GRAYSCALE_HEIGHT, BINARY_MASK, GRAYSCALE_MASK -> { - if (colorMode != IrisImageColorMode.GRAYSCALE) { - diagnostics.add(type + " requires a grayscale PNG, got " + colorMode); - } - if (bitDepth != 8 && bitDepth != 16) { - diagnostics.add(type + " requires 8-bit or 16-bit grayscale samples, got " + bitDepth + "-bit"); - } - } - case RGB_HEIGHT, COLOR_MAP -> { - if (colorMode != IrisImageColorMode.RGB && colorMode != IrisImageColorMode.RGBA) { - diagnostics.add(type + " requires an RGB or RGBA PNG, got " + colorMode); - } - if (bitDepth != 8) { - diagnostics.add(type + " requires canonical 8-bit RGB channels, got " + bitDepth + "-bit"); - } - } - case ALPHA_MASK -> { - if (colorMode != IrisImageColorMode.RGBA || !image.hasAlpha()) { - diagnostics.add("ALPHA_MASK requires an 8-bit RGBA PNG"); - } - if (bitDepth != 8) { - diagnostics.add("ALPHA_MASK requires an 8-bit alpha channel, got " + bitDepth + "-bit color channels"); - } - if (definition.getAlpha() != null && definition.getAlpha() != IrisImageMapAlpha.IGNORE) { - diagnostics.add("ALPHA_MASK requires alpha=IGNORE because alpha is the map data"); - } - } - } - - if ((type == IrisImageMapType.COLOR_MAP || type == IrisImageMapType.BINARY_MASK) - && definition.getSampling() != null - && definition.getSampling() != IrisImageMapSampling.NEAREST) { - diagnostics.add(type + " requires NEAREST sampling"); - } - if (type == IrisImageMapType.COLOR_MAP && definition.getSmoothingRadius() != 0) { - diagnostics.add("COLOR_MAP does not support numeric smoothing"); - } - } - - private static void validateLegend(IrisImageMap definition, List diagnostics) { - KMap colors = definition.getColors(); - if (definition.getType() != IrisImageMapType.COLOR_MAP) { - if (colors != null && !colors.isEmpty()) { - diagnostics.add("colors may only be set for COLOR_MAP definitions"); - } - if (definition.getColorTolerance() != 0D) { - diagnostics.add("colorTolerance may only be set for COLOR_MAP definitions"); - } - return; - } - if (colors == null || colors.isEmpty()) { - diagnostics.add("COLOR_MAP requires at least one #RRGGBB legend entry"); - return; - } - - Map decoded = new HashMap<>(); - for (Map.Entry entry : colors.entrySet()) { - String encoded = entry.getKey(); - String target = entry.getValue(); - if (encoded == null || !COLOR_PATTERN.matcher(encoded).matches()) { - diagnostics.add("Color legend key must use exact #RRGGBB syntax, got " + encoded); - continue; - } - if (target == null || target.isBlank()) { - diagnostics.add("Color legend target for " + encoded + " must not be blank"); - } - int rgb = Integer.parseInt(encoded.substring(1), 16); - String previous = decoded.putIfAbsent(rgb, encoded); - if (previous != null) { - diagnostics.add("Color legend duplicates raw color " + previous + " as " + encoded); - } - } - - boolean fallbackRequired = definition.getOutOfBounds() == IrisImageMapOutOfBounds.FALLBACK - || definition.getUnknownColor() == IrisImageMapUnknownColor.FALLBACK - || definition.getAlpha() == IrisImageMapAlpha.TRANSPARENT_IS_FALLBACK - || definition.getAlpha() == IrisImageMapAlpha.MASK; - if (fallbackRequired && (definition.getFallbackTarget() == null || definition.getFallbackTarget().isBlank())) { - diagnostics.add("fallbackTarget is required by the configured color-map fallback policy"); - } - } - - private static CompiledIrisImageMap.FloatTiles compileScalars(IrisImageMap definition, IrisImage image) { - int width = image.getWidth(); - int height = image.getHeight(); - CompiledIrisImageMap.FloatTiles values = new CompiledIrisImageMap.FloatTiles( - Math.multiplyExact(width, height) - ); - for (int sourceZ = 0; sourceZ < height; sourceZ++) { - for (int sourceX = 0; sourceX < width; sourceX++) { - double alpha = image.getAlphaNormalized(sourceX, sourceZ); - validateAlphaPixel(definition, sourceX, sourceZ, alpha); - double value; - if (definition.getAlpha() == IrisImageMapAlpha.TRANSPARENT_IS_FALLBACK && alpha == 0D) { - value = definition.getFallbackValue(); - } else { - value = rawScalar(definition.getType(), image, sourceX, sourceZ); - if (definition.isInverted()) { - value = 1D - value; - } - value = Math.pow(clamp01(value), definition.getCurveExponent()); - if (definition.getType() == IrisImageMapType.BINARY_MASK) { - value = threshold(value, definition.getThreshold(), definition.getFalloff()); - } - if (definition.getAlpha() == IrisImageMapAlpha.MASK) { - value *= alpha; - } - } - values.set((sourceZ * width) + sourceX, (float) clamp01(value)); - } - } - return values; - } - - private static double rawScalar(IrisImageMapType type, IrisImage image, int sourceX, int sourceZ) { - return switch (type) { - case GRAYSCALE_HEIGHT, BINARY_MASK, GRAYSCALE_MASK -> image.getBandNormalized(sourceX, sourceZ, 0); - case RGB_HEIGHT -> { - int red = image.getBandSample(sourceX, sourceZ, 0); - int green = image.getBandSample(sourceX, sourceZ, 1); - int blue = image.getBandSample(sourceX, sourceZ, 2); - int encoded = (red << 16) | (green << 8) | blue; - yield encoded / 16_777_215D; - } - case ALPHA_MASK -> image.getAlphaNormalized(sourceX, sourceZ); - case COLOR_MAP -> throw new IrisImageMapValidationException("COLOR_MAP does not produce scalar pixels"); - }; - } - - private static CompiledTargets compileTargets(IrisImageMap definition, IrisImage image) { - Legend legend = compileLegend(definition); - int width = image.getWidth(); - int height = image.getHeight(); - CompiledIrisImageMap.IntTiles indices = new CompiledIrisImageMap.IntTiles( - Math.multiplyExact(width, height) - ); - int unknownColorPixelCount = 0; - for (int sourceZ = 0; sourceZ < height; sourceZ++) { - for (int sourceX = 0; sourceX < width; sourceX++) { - double alpha = image.getAlphaNormalized(sourceX, sourceZ); - validateAlphaPixel(definition, sourceX, sourceZ, alpha); - int targetIndex; - if (definition.getAlpha() == IrisImageMapAlpha.TRANSPARENT_IS_FALLBACK && alpha == 0D) { - targetIndex = legend.fallbackIndex(); - } else if (definition.getAlpha() == IrisImageMapAlpha.MASK && alpha < 1D) { - if (alpha == 0D) { - targetIndex = legend.fallbackIndex(); - } else { - throw new IrisImageMapValidationException( - "COLOR_MAP alpha=MASK requires binary alpha; pixel " + sourceX + "," + sourceZ - + " has alpha " + alpha - ); - } - } else { - int rgb = image.getRawRgb8(sourceX, sourceZ); - TargetMatch match = matchTarget(definition, legend, rgb, sourceX, sourceZ); - targetIndex = match.targetIndex(); - if (match.unknown()) { - unknownColorPixelCount++; - } - } - indices.set((sourceZ * width) + sourceX, targetIndex); - } - } - return new CompiledTargets(indices, legend.targets(), unknownColorPixelCount); - } - - private static Legend compileLegend(IrisImageMap definition) { - List entries = new ArrayList<>(); - for (Map.Entry entry : definition.getColors().entrySet()) { - int rgb = Integer.parseInt(entry.getKey().substring(1), 16); - entries.add(new MutableLegendEntry(rgb, entry.getKey().toUpperCase(), entry.getValue())); - } - entries.sort(Comparator.comparingInt(MutableLegendEntry::rgb).thenComparing(MutableLegendEntry::target)); - - LinkedHashMap targetIndexes = new LinkedHashMap<>(); - Map exact = new HashMap<>(); - List compiled = new ArrayList<>(); - for (MutableLegendEntry entry : entries) { - int targetIndex = targetIndexes.computeIfAbsent(entry.target(), ignored -> targetIndexes.size()); - LegendEntry compiledEntry = new LegendEntry(entry.rgb(), entry.encoded(), entry.target(), targetIndex); - exact.put(entry.rgb(), compiledEntry); - compiled.add(compiledEntry); - } - - int fallbackIndex = -1; - if (definition.getFallbackTarget() != null && !definition.getFallbackTarget().isBlank()) { - fallbackIndex = targetIndexes.computeIfAbsent( - definition.getFallbackTarget(), - ignored -> targetIndexes.size() - ); - } - String[] targets = new String[targetIndexes.size()]; - for (Map.Entry entry : targetIndexes.entrySet()) { - targets[entry.getValue()] = entry.getKey(); - } - return new Legend(List.copyOf(compiled), Map.copyOf(exact), targets, fallbackIndex); - } - - private static TargetMatch matchTarget( - IrisImageMap definition, - Legend legend, - int rgb, - int sourceX, - int sourceZ - ) { - LegendEntry exact = legend.exact().get(rgb); - if (exact != null) { - return new TargetMatch(exact.targetIndex(), false); - } - - double toleranceSquared = definition.getColorTolerance() * definition.getColorTolerance(); - LegendEntry matched = null; - List ambiguous = new ArrayList<>(); - if (toleranceSquared > 0D) { - for (LegendEntry candidate : legend.entries()) { - if (colorDistanceSquared(rgb, candidate.rgb()) <= toleranceSquared) { - if (matched == null) { - matched = candidate; - } - ambiguous.add(candidate.encoded()); - } - } - } - if (ambiguous.size() > 1) { - throw new IrisImageMapValidationException( - "Color " + encodeColor(rgb) + " at " + sourceX + "," + sourceZ - + " ambiguously matches " + String.join(", ", ambiguous) - ); - } - if (matched != null) { - return new TargetMatch(matched.targetIndex(), false); - } - - int targetIndex = switch (definition.getUnknownColor()) { - case ERROR -> throw new IrisImageMapValidationException( - "Color " + encodeColor(rgb) + " at " + sourceX + "," + sourceZ + " is absent from the legend" - ); - case FALLBACK -> legend.fallbackIndex(); - case IGNORE -> -1; - }; - return new TargetMatch(targetIndex, true); - } - - private static int countClippedPixels( - IrisImageMap definition, - CompiledIrisImageMap.FloatTiles values, - int size - ) { - if (!definition.isClamp() - || (definition.getType() != IrisImageMapType.GRAYSCALE_HEIGHT - && definition.getType() != IrisImageMapType.RGB_HEIGHT)) { - return 0; - } - double minimum = definition.getMinimumHeight(); - double maximum = definition.getMaximumHeight(); - double range = maximum - minimum; - double offset = definition.getVerticalOffset(); - int clipped = 0; - for (int index = 0; index < size; index++) { - double height = minimum + (values.get(index) * range) + offset; - if (height < minimum || height > maximum) { - clipped++; - } - } - return clipped; - } - - private static void validateAlphaPixel(IrisImageMap definition, int sourceX, int sourceZ, double alpha) { - if (definition.getAlpha() == IrisImageMapAlpha.ERROR && alpha < 1D) { - throw new IrisImageMapValidationException( - "Transparent pixel at " + sourceX + "," + sourceZ + " violates alpha=ERROR" - ); - } - } - - private static double threshold(double value, double threshold, double falloff) { - if (falloff == 0D) { - return value >= threshold ? 1D : 0D; - } - return clamp01((value - threshold) / falloff); - } - - private static void smooth(CompiledIrisImageMap.FloatTiles values, int width, int height, int radius) { - float[] line = new float[Math.max(width, height)]; - int diameter = (radius * 2) + 1; - for (int sourceZ = 0; sourceZ < height; sourceZ++) { - int rowOffset = sourceZ * width; - for (int sourceX = 0; sourceX < width; sourceX++) { - line[sourceX] = values.get(rowOffset + sourceX); - } - double sum = 0D; - for (int offset = -radius; offset <= radius; offset++) { - int sourceX = Math.max(0, Math.min(width - 1, offset)); - sum += line[sourceX]; - } - for (int sourceX = 0; sourceX < width; sourceX++) { - values.set(rowOffset + sourceX, (float) (sum / diameter)); - int leavingX = Math.max(0, Math.min(width - 1, sourceX - radius)); - int enteringX = Math.max(0, Math.min(width - 1, sourceX + radius + 1)); - sum += line[enteringX] - line[leavingX]; - } - } - - for (int sourceX = 0; sourceX < width; sourceX++) { - for (int sourceZ = 0; sourceZ < height; sourceZ++) { - line[sourceZ] = values.get((sourceZ * width) + sourceX); - } - double sum = 0D; - for (int offset = -radius; offset <= radius; offset++) { - int sourceZ = Math.max(0, Math.min(height - 1, offset)); - sum += line[sourceZ]; - } - for (int sourceZ = 0; sourceZ < height; sourceZ++) { - values.set((sourceZ * width) + sourceX, (float) (sum / diameter)); - int leavingZ = Math.max(0, Math.min(height - 1, sourceZ - radius)); - int enteringZ = Math.max(0, Math.min(height - 1, sourceZ + radius + 1)); - sum += line[enteringZ] - line[leavingZ]; - } - } - } - - private static SourceDigest hashSource(IrisImage image) { - HashAccumulator hash = new HashAccumulator(); - hash.addString(image.getFormat()); - hash.addString(image.getColorMode().name()); - hash.addInt(image.getWidth()); - hash.addInt(image.getHeight()); - hash.addInt(image.getColorComponentCount()); - hash.addInt(image.getChannelCount()); - hash.addInt(image.getBitDepth()); - hash.addBoolean(image.hasAlpha()); - double minimumAlpha = 1D; - double maximumAlpha = image.hasAlpha() ? 0D : 1D; - for (int sourceZ = 0; sourceZ < image.getHeight(); sourceZ++) { - for (int sourceX = 0; sourceX < image.getWidth(); sourceX++) { - double alpha = image.getAlphaNormalized(sourceX, sourceZ); - minimumAlpha = Math.min(minimumAlpha, alpha); - maximumAlpha = Math.max(maximumAlpha, alpha); - for (int band = 0; band < image.getChannelCount(); band++) { - hash.addInt(image.getBandSample(sourceX, sourceZ, band)); - } - } - } - return new SourceDigest(hash.finish(), minimumAlpha, maximumAlpha); - } - - private static String hashContent(IrisImageMap definition, IrisImageMapSourceMetadata metadata) { - HashAccumulator hash = new HashAccumulator(); - hash.addString(metadata.decodedContentHash()); - hash.addString(definition.getSource()); - hash.addString(definition.getType().name()); - hash.addDouble(definition.getBlocksPerPixel()); - hash.addDouble(definition.getOrigin().getX()); - hash.addDouble(definition.getOrigin().getZ()); - hash.addDouble(definition.getSourceOrigin().getX()); - hash.addDouble(definition.getSourceOrigin().getZ()); - hash.addString(definition.getRotation().name()); - hash.addBoolean(definition.isMirrorX()); - hash.addBoolean(definition.isMirrorZ()); - hash.addString(definition.getSampling().name()); - hash.addString(definition.getOutOfBounds().name()); - hash.addDouble(definition.getFallbackValue()); - hash.addString(definition.getFallbackTarget()); - hash.addString(definition.getAlpha().name()); - hash.addDouble(definition.getMinimumHeight()); - hash.addDouble(definition.getMaximumHeight()); - hash.addDouble(definition.getVerticalOffset()); - hash.addBoolean(definition.isClamp()); - hash.addBoolean(definition.isInverted()); - hash.addDouble(definition.getCurveExponent()); - hash.addInt(definition.getSmoothingRadius()); - hash.addDouble(definition.getThreshold()); - hash.addDouble(definition.getFalloff()); - hash.addDouble(definition.getColorTolerance()); - hash.addString(definition.getUnknownColor().name()); - - KMap configuredColors = definition.getColors(); - List> colors = configuredColors == null - ? new ArrayList<>() - : new ArrayList<>(configuredColors.entrySet()); - colors.sort(Map.Entry.comparingByKey(String.CASE_INSENSITIVE_ORDER)); - hash.addInt(colors.size()); - for (Map.Entry entry : colors) { - hash.addString(entry.getKey().toUpperCase()); - hash.addString(entry.getValue()); - } - return hash.finish(); - } - - private static CompiledIrisImageMap.SourceTransform compileSourceTransform(IrisImageMap definition) { - double sourceXFromWorldX; - double sourceXFromWorldZ; - double sourceZFromWorldX; - double sourceZFromWorldZ; - switch (definition.getRotation()) { - case DEG_0 -> { - sourceXFromWorldX = 1D; - sourceXFromWorldZ = 0D; - sourceZFromWorldX = 0D; - sourceZFromWorldZ = 1D; - } - case DEG_90 -> { - sourceXFromWorldX = 0D; - sourceXFromWorldZ = 1D; - sourceZFromWorldX = -1D; - sourceZFromWorldZ = 0D; - } - case DEG_180 -> { - sourceXFromWorldX = -1D; - sourceXFromWorldZ = 0D; - sourceZFromWorldX = 0D; - sourceZFromWorldZ = -1D; - } - case DEG_270 -> { - sourceXFromWorldX = 0D; - sourceXFromWorldZ = -1D; - sourceZFromWorldX = 1D; - sourceZFromWorldZ = 0D; - } - default -> throw new IrisImageMapValidationException( - "Unsupported image-map rotation " + definition.getRotation() - ); - } - if (definition.isMirrorX()) { - sourceXFromWorldX = -sourceXFromWorldX; - sourceXFromWorldZ = -sourceXFromWorldZ; - } - if (definition.isMirrorZ()) { - sourceZFromWorldX = -sourceZFromWorldX; - sourceZFromWorldZ = -sourceZFromWorldZ; - } - double inverseScale = 1D / definition.getBlocksPerPixel(); - sourceXFromWorldX *= inverseScale; - sourceXFromWorldZ *= inverseScale; - sourceZFromWorldX *= inverseScale; - sourceZFromWorldZ *= inverseScale; - double sourceXOffset = definition.getSourceOrigin().getX() - - (sourceXFromWorldX * definition.getOrigin().getX()) - - (sourceXFromWorldZ * definition.getOrigin().getZ()); - double sourceZOffset = definition.getSourceOrigin().getZ() - - (sourceZFromWorldX * definition.getOrigin().getX()) - - (sourceZFromWorldZ * definition.getOrigin().getZ()); - if (!Double.isFinite(sourceXFromWorldX) - || !Double.isFinite(sourceXFromWorldZ) - || !Double.isFinite(sourceXOffset) - || !Double.isFinite(sourceZFromWorldX) - || !Double.isFinite(sourceZFromWorldZ) - || !Double.isFinite(sourceZOffset)) { - throw new IrisImageMapValidationException("Image-map coordinate transform must remain finite"); - } - return new CompiledIrisImageMap.SourceTransform( - sourceXFromWorldX, - sourceXFromWorldZ, - sourceXOffset, - sourceZFromWorldX, - sourceZFromWorldZ, - sourceZOffset - ); - } - - private static IrisImageMap snapshot(IrisImageMap definition) { - KMap configuredColors = definition.getColors(); - KMap colors = configuredColors == null ? new KMap<>() : new KMap<>(configuredColors); - return new IrisImageMap() - .setSource(definition.getSource()) - .setType(definition.getType()) - .setBlocksPerPixel(definition.getBlocksPerPixel()) - .setOrigin(new IrisImageMapOrigin(definition.getOrigin().getX(), definition.getOrigin().getZ())) - .setSourceOrigin(new IrisImageMapOrigin( - definition.getSourceOrigin().getX(), - definition.getSourceOrigin().getZ() - )) - .setRotation(definition.getRotation()) - .setMirrorX(definition.isMirrorX()) - .setMirrorZ(definition.isMirrorZ()) - .setSampling(definition.getSampling()) - .setOutOfBounds(definition.getOutOfBounds()) - .setFallbackValue(definition.getFallbackValue()) - .setFallbackTarget(definition.getFallbackTarget()) - .setAlpha(definition.getAlpha()) - .setMinimumHeight(definition.getMinimumHeight()) - .setMaximumHeight(definition.getMaximumHeight()) - .setVerticalOffset(definition.getVerticalOffset()) - .setClamp(definition.isClamp()) - .setInverted(definition.isInverted()) - .setCurveExponent(definition.getCurveExponent()) - .setSmoothingRadius(definition.getSmoothingRadius()) - .setThreshold(definition.getThreshold()) - .setFalloff(definition.getFalloff()) - .setColorTolerance(definition.getColorTolerance()) - .setUnknownColor(definition.getUnknownColor()) - .setColors(colors); - } - - private static double colorDistanceSquared(int first, int second) { - int red = ((first >>> 16) & 0xFF) - ((second >>> 16) & 0xFF); - int green = ((first >>> 8) & 0xFF) - ((second >>> 8) & 0xFF); - int blue = (first & 0xFF) - (second & 0xFF); - return (red * red) + (green * green) + (blue * blue); - } - - private static String encodeColor(int rgb) { - return String.format(Locale.ROOT, "#%06X", rgb & 0xFFFFFF); - } - - private static boolean finiteAtLeast(double value, double minimum) { - return Double.isFinite(value) && value >= minimum; - } - - private static boolean range(double value, double minimum, double maximum) { - return Double.isFinite(value) && value >= minimum && value <= maximum; - } - - private static double clamp01(double value) { - return Math.max(0D, Math.min(1D, value)); - } - - private record MutableLegendEntry(int rgb, String encoded, String target) { - } - - private record LegendEntry(int rgb, String encoded, String target, int targetIndex) { - } - - private record Legend( - List entries, - Map exact, - String[] targets, - int fallbackIndex - ) { - } - - private record CompiledTargets( - CompiledIrisImageMap.IntTiles indices, - String[] targets, - int unknownColorPixelCount - ) { - } - - private record TargetMatch(int targetIndex, boolean unknown) { - } - - private record SourceDigest(String hash, double minimumAlpha, double maximumAlpha) { - } - - private static final class HashAccumulator { - private final MessageDigest digest; - - private HashAccumulator() { - try { - digest = MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 is unavailable", exception); - } - } - - private void addBoolean(boolean value) { - digest.update((byte) (value ? 1 : 0)); - } - - private void addInt(int value) { - digest.update((byte) (value >>> 24)); - digest.update((byte) (value >>> 16)); - digest.update((byte) (value >>> 8)); - digest.update((byte) value); - } - - private void addLong(long value) { - digest.update((byte) (value >>> 56)); - digest.update((byte) (value >>> 48)); - digest.update((byte) (value >>> 40)); - digest.update((byte) (value >>> 32)); - digest.update((byte) (value >>> 24)); - digest.update((byte) (value >>> 16)); - digest.update((byte) (value >>> 8)); - digest.update((byte) value); - } - - private void addDouble(double value) { - addLong(Double.doubleToLongBits(value)); - } - - private void addString(String value) { - if (value == null) { - addInt(-1); - return; - } - byte[] bytes = value.getBytes(StandardCharsets.UTF_8); - addInt(bytes.length); - digest.update(bytes); - } - - private String finish() { - return HexFormat.of().formatHex(digest.digest()); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/image/IrisImageMapMaskSampler.java b/src/main/java/art/arcane/iris/engine/image/IrisImageMapMaskSampler.java deleted file mode 100644 index 5171993c1..000000000 --- a/src/main/java/art/arcane/iris/engine/image/IrisImageMapMaskSampler.java +++ /dev/null @@ -1,113 +0,0 @@ -package art.arcane.iris.engine.image; - -import art.arcane.iris.engine.object.image.IrisImageMapMask; -import art.arcane.iris.engine.object.image.IrisImageMapMaskOperation; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -public final class IrisImageMapMaskSampler { - private static final IrisImageMapMaskSampler EMPTY = new IrisImageMapMaskSampler(List.of()); - - private final List layers; - - public IrisImageMapMaskSampler(List layers) { - this.layers = List.copyOf(Objects.requireNonNull(layers, "Image-map mask layers")); - } - - public static IrisImageMapMaskSampler empty() { - return EMPTY; - } - - public static Layer layer(CompiledIrisImageMap compiled, IrisImageMapMask definition) { - Objects.requireNonNull(definition, "Image-map mask definition"); - if (definition.getOperation() == null) { - throw new IrisImageMapValidationException("Image-map mask operation is required"); - } - if (!unitRange(definition.getThreshold()) || !unitRange(definition.getFalloff())) { - throw new IrisImageMapValidationException("Image-map mask threshold and falloff must be within 0..1"); - } - return new Layer( - Objects.requireNonNull(compiled, "Compiled image-map mask"), - definition.getOperation(), - definition.isInverted(), - definition.getThreshold(), - definition.getFalloff() - ); - } - - public static IrisImageMapMaskSampler of( - List compiled, - List definitions - ) { - if (compiled.size() != definitions.size()) { - throw new IllegalArgumentException("Compiled image-map masks and definitions must have equal sizes"); - } - List layers = new ArrayList<>(compiled.size()); - for (int index = 0; index < compiled.size(); index++) { - layers.add(layer(compiled.get(index), definitions.get(index))); - } - return layers.isEmpty() ? empty() : new IrisImageMapMaskSampler(layers); - } - - public boolean isEmpty() { - return layers.isEmpty(); - } - - public double sample(double worldX, double worldZ) { - double weight = 1D; - for (Layer layer : layers) { - double value = layer.sample(worldX, worldZ); - weight = switch (layer.operation()) { - case MULTIPLY -> weight * value; - case MINIMUM -> Math.min(weight, value); - case MAXIMUM -> Math.max(weight, value); - case ADD -> weight + value; - case SUBTRACT -> weight - value; - }; - weight = clamp01(weight); - } - return weight; - } - - private static boolean unitRange(double value) { - return Double.isFinite(value) && value >= 0D && value <= 1D; - } - - private static double clamp01(double value) { - return Math.max(0D, Math.min(1D, value)); - } - - public record Layer( - CompiledIrisImageMap compiled, - IrisImageMapMaskOperation operation, - boolean inverted, - double threshold, - double falloff - ) { - public Layer { - Objects.requireNonNull(compiled, "Compiled image-map mask"); - Objects.requireNonNull(operation, "Image-map mask operation"); - if (!unitRange(threshold) || !unitRange(falloff)) { - throw new IrisImageMapValidationException( - "Image-map mask threshold and falloff must be within 0..1" - ); - } - } - - private double sample(double worldX, double worldZ) { - double value = compiled.sampleNormalized(worldX, worldZ); - if (inverted) { - value = 1D - value; - } - if (threshold == 0D && falloff == 0D) { - return value; - } - if (falloff == 0D) { - return value >= threshold ? 1D : 0D; - } - return clamp01((value - threshold) / falloff); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/image/IrisImageMapRuntime.java b/src/main/java/art/arcane/iris/engine/image/IrisImageMapRuntime.java deleted file mode 100644 index 8cf796869..000000000 --- a/src/main/java/art/arcane/iris/engine/image/IrisImageMapRuntime.java +++ /dev/null @@ -1,386 +0,0 @@ -package art.arcane.iris.engine.image; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.image.IrisImage; -import art.arcane.iris.engine.object.image.IrisImageMap; -import art.arcane.iris.engine.object.image.IrisImageMapApplication; -import art.arcane.iris.engine.object.image.IrisImageMapBinding; -import art.arcane.iris.engine.object.image.IrisImageMapMask; -import art.arcane.iris.engine.object.image.IrisImageMapType; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.world.biome.InferredType; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; - -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -public final class IrisImageMapRuntime { - private final int minimumWorldHeight; - private final Map bindings; - private final Map applications; - private final Set mappedRegions; - private final Set mappedBiomes; - - private IrisImageMapRuntime( - int minimumWorldHeight, - Map bindings, - Map applications, - Set mappedRegions, - Set mappedBiomes - ) { - this.minimumWorldHeight = minimumWorldHeight; - this.bindings = Map.copyOf(bindings); - this.applications = Map.copyOf(applications); - this.mappedRegions = Set.copyOf(mappedRegions); - this.mappedBiomes = Set.copyOf(mappedBiomes); - } - - public static IrisImageMapRuntime compile(Engine engine) { - Objects.requireNonNull(engine, "Image-map runtime requires an engine"); - return compile(engine.getData(), engine.getDimension(), engine.getMinHeight()); - } - - public static IrisImageMapRuntime compile(IrisData data, IrisDimension dimension, int minimumWorldHeight) { - Objects.requireNonNull(data, "Image-map runtime requires Iris data"); - Objects.requireNonNull(dimension, "Image-map runtime requires a dimension"); - Map bindings = new LinkedHashMap<>(); - Map applications = new EnumMap<>(IrisImageMapApplication.class); - Set mappedRegions = new LinkedHashSet<>(); - Set mappedBiomes = new LinkedHashSet<>(); - - for (IrisImageMapBinding binding : dimension.getImageMaps()) { - RuntimeBinding runtimeBinding = compileBinding(binding, data, dimension, mappedRegions, mappedBiomes); - RuntimeBinding duplicate = bindings.putIfAbsent(runtimeBinding.key, runtimeBinding); - if (duplicate != null) { - throw validation("Duplicate dimension image-map key '" + runtimeBinding.key + "'"); - } - IrisImageMapApplication application = runtimeBinding.application; - if (application != IrisImageMapApplication.MASK && application != IrisImageMapApplication.CUSTOM) { - RuntimeBinding applicationDuplicate = applications.putIfAbsent(application, runtimeBinding); - if (applicationDuplicate != null) { - throw validation("Dimension declares more than one " + application + " image-map binding"); - } - } - } - - for (RuntimeBinding binding : bindings.values()) { - binding.masks = resolveMasks(binding, bindings); - } - - return new IrisImageMapRuntime( - minimumWorldHeight, bindings, applications, mappedRegions, mappedBiomes - ); - } - - public boolean has(IrisImageMapApplication application) { - return applications.containsKey(application); - } - - public Set getMappedRegions() { - return mappedRegions; - } - - public Set getMappedBiomes() { - return mappedBiomes; - } - - public double sampleTerrainHeight(double worldX, double worldZ, double proceduralLocalHeight) { - RuntimeBinding binding = applications.get(IrisImageMapApplication.TERRAIN_HEIGHT); - if (binding == null) { - return proceduralLocalHeight; - } - double mappedLocalHeight = binding.compiled.sampleHeight(worldX, worldZ) - minimumWorldHeight; - double weight = binding.maskWeight(worldX, worldZ); - return blendTerrainHeight(mappedLocalHeight, proceduralLocalHeight, weight); - } - - public IrisRegion sampleRegion(double worldX, double worldZ) { - RuntimeBinding binding = applications.get(IrisImageMapApplication.REGION); - if (binding == null || !selectCategorical(binding.maskWeight(worldX, worldZ))) { - return null; - } - String target = binding.compiled.sampleTarget(worldX, worldZ); - return target == null ? null : binding.regions.get(target); - } - - public IrisBiome sampleBiome(double worldX, double worldZ) { - RuntimeBinding binding = applications.get(IrisImageMapApplication.BIOME); - if (binding == null || !selectCategorical(binding.maskWeight(worldX, worldZ))) { - return null; - } - String target = binding.compiled.sampleTarget(worldX, worldZ); - return target == null ? null : binding.biomes.get(target); - } - - public PlatformBlockState sampleSurfaceBlock(double worldX, double worldZ) { - RuntimeBinding binding = applications.get(IrisImageMapApplication.SURFACE_BLOCK); - if (binding == null || !selectCategorical(binding.maskWeight(worldX, worldZ))) { - return null; - } - String target = binding.compiled.sampleTarget(worldX, worldZ); - return target == null ? null : binding.blocks.get(target); - } - - public CompiledIrisImageMap getCompiled(String key) { - RuntimeBinding binding = bindings.get(key); - return binding == null ? null : binding.compiled; - } - - public static double blendTerrainHeight(double mappedLocalHeight, double proceduralLocalHeight, double weight) { - return proceduralLocalHeight + ((mappedLocalHeight - proceduralLocalHeight) * weight); - } - - public static boolean selectCategorical(double weight) { - return weight >= 0.5D; - } - - private static RuntimeBinding compileBinding( - IrisImageMapBinding binding, - IrisData data, - IrisDimension dimension, - Set mappedRegions, - Set mappedBiomes - ) { - if (binding == null) { - throw validation("Dimension imageMaps contains a null binding"); - } - String key = requireText(binding.getKey(), "Dimension image-map key"); - String mapKey = requireText(binding.getMap(), "Dimension image-map resource for '" + key + "'"); - IrisImageMapApplication application = binding.getApplication(); - if (application == null) { - throw validation("Dimension image-map '" + key + "' requires an application"); - } - IrisImageMap definition = data.getImageMapLoader().load(mapKey); - if (definition == null) { - throw validation("Dimension image-map '" + key + "' references missing image-map resource '" + mapKey + "'"); - } - String source = requireText(definition.getSource(), "Image-map resource '" + mapKey + "' source"); - IrisImage image = data.getImageLoader().load(source); - if (image == null) { - throw validation("Image-map resource '" + mapKey + "' references missing or invalid PNG '" + source + "'"); - } - CompiledIrisImageMap compiled; - try { - validateApplication(key, application, definition.getType(), binding.getMasks()); - compiled = CompiledIrisImageMap.compile(definition, image); - } finally { - data.getImageLoader().unload(source); - } - Map regions = new LinkedHashMap<>(); - Map biomes = new LinkedHashMap<>(); - Map blocks = new LinkedHashMap<>(); - Set targets = legendTargets(definition); - - if (application == IrisImageMapApplication.REGION) { - for (String target : targets) { - IrisRegion region = data.getRegionLoader().load(localResourceKey(target)); - if (region == null) { - throw validation("Image-map '" + key + "' references missing region target '" + target + "'"); - } - regions.put(target, region); - mappedRegions.add(region); - } - } else if (application == IrisImageMapApplication.BIOME) { - for (String target : targets) { - String localTarget = localResourceKey(target); - IrisBiome biome = data.getBiomeLoader().load(localTarget); - if (biome == null) { - throw validation("Image-map '" + key + "' references missing biome target '" + target + "'"); - } - IrisBiome typedBiome = biome.withInferredType(resolveBiomeType(localTarget, dimension, data)); - biomes.put(target, typedBiome); - mappedBiomes.add(typedBiome); - } - } else if (application == IrisImageMapApplication.SURFACE_BLOCK) { - for (String target : targets) { - PlatformBlockState block = B.getStateOrNull(target, false); - if (block == null) { - throw validation("Image-map '" + key + "' references unknown surface block target '" + target + "'"); - } - blocks.put(target, block); - } - } - - return new RuntimeBinding( - key, - application, - compiled, - Map.copyOf(regions), - Map.copyOf(biomes), - Map.copyOf(blocks), - binding.getMasks() == null ? List.of() : List.copyOf(binding.getMasks()) - ); - } - - private static void validateApplication( - String key, - IrisImageMapApplication application, - IrisImageMapType type, - List masks - ) { - if (type == null) { - throw validation("Image-map '" + key + "' requires a type"); - } - boolean valid = switch (application) { - case TERRAIN_HEIGHT -> type == IrisImageMapType.GRAYSCALE_HEIGHT - || type == IrisImageMapType.RGB_HEIGHT; - case BIOME, REGION, SURFACE_BLOCK -> type == IrisImageMapType.COLOR_MAP; - case MASK -> isMaskType(type); - case CUSTOM -> true; - }; - if (!valid) { - throw validation("Image-map '" + key + "' type " + type + " is incompatible with " + application); - } - if (application == IrisImageMapApplication.MASK && masks != null && !masks.isEmpty()) { - throw validation("MASK image-map '" + key + "' cannot reference additional masks"); - } - } - - private static IrisImageMapMaskSampler resolveMasks( - RuntimeBinding binding, - Map bindings - ) { - if (binding.maskDefinitions.isEmpty()) { - return IrisImageMapMaskSampler.empty(); - } - List masks = new ArrayList<>(binding.maskDefinitions.size()); - for (IrisImageMapMask mask : binding.maskDefinitions) { - if (mask == null) { - throw validation("Image-map '" + binding.key + "' contains a null mask reference"); - } - String maskKey = requireText(mask.getMap(), "Mask reference on image-map '" + binding.key + "'"); - RuntimeBinding maskBinding = bindings.get(maskKey); - if (maskBinding == null) { - throw validation("Image-map '" + binding.key + "' references missing MASK binding '" + maskKey + "'"); - } - if (maskBinding.application != IrisImageMapApplication.MASK) { - throw validation("Image-map '" + binding.key + "' references '" + maskKey + "', which is not a MASK binding"); - } - if (mask.getOperation() == null) { - throw validation("Mask '" + maskKey + "' on image-map '" + binding.key + "' requires an operation"); - } - if (!range(mask.getThreshold()) || !range(mask.getFalloff())) { - throw validation("Mask '" + maskKey + "' threshold and falloff must be finite values within 0..1"); - } - masks.add(IrisImageMapMaskSampler.layer(maskBinding.compiled, mask)); - } - return new IrisImageMapMaskSampler(masks); - } - - private static Set legendTargets(IrisImageMap definition) { - Set targets = new LinkedHashSet<>(); - if (definition.getColors() != null) { - for (String target : definition.getColors().values()) { - if (target != null && !target.isBlank()) { - targets.add(target); - } - } - } - String fallback = definition.getFallbackTarget(); - if (fallback != null && !fallback.isBlank()) { - targets.add(fallback); - } - return targets; - } - - private static InferredType resolveBiomeType(String biomeKey, IrisDimension dimension, IrisData data) { - Set types = new LinkedHashSet<>(); - for (IrisRegion region : dimension.getAllRegions(() -> data)) { - if (region == null) { - continue; - } - if (region.getLandBiomes().contains(biomeKey)) { - types.add(InferredType.LAND); - } - if (region.getSeaBiomes().contains(biomeKey)) { - types.add(InferredType.SEA); - } - if (region.getShoreBiomes().contains(biomeKey)) { - types.add(InferredType.SHORE); - } - } - if (types.size() != 1) { - throw validation("Image-mapped biome '" + biomeKey - + "' must occur in exactly one landBiomes, seaBiomes, or shoreBiomes role across the dimension; found " - + types); - } - return types.iterator().next(); - } - - private static String localResourceKey(String target) { - String normalized = requireText(target, "Image-map Iris resource target"); - int separator = normalized.indexOf(':'); - if (separator < 0) { - return normalized; - } - if (!normalized.startsWith("iris:") || separator == normalized.length() - 1) { - throw validation("Iris biome and region targets must be bare pack keys or use the iris: namespace, got '" - + target + "'"); - } - return normalized.substring(separator + 1); - } - - private static String requireText(String value, String name) { - if (value == null || value.isBlank()) { - throw validation(name + " must not be blank"); - } - return value.trim(); - } - - private static boolean range(double value) { - return Double.isFinite(value) && value >= 0D && value <= 1D; - } - - private static boolean isMaskType(IrisImageMapType type) { - return type == IrisImageMapType.BINARY_MASK - || type == IrisImageMapType.GRAYSCALE_MASK - || type == IrisImageMapType.ALPHA_MASK; - } - - private static IrisImageMapValidationException validation(String message) { - return new IrisImageMapValidationException(message); - } - - private static final class RuntimeBinding { - private final String key; - private final IrisImageMapApplication application; - private final CompiledIrisImageMap compiled; - private final Map regions; - private final Map biomes; - private final Map blocks; - private final List maskDefinitions; - private IrisImageMapMaskSampler masks = IrisImageMapMaskSampler.empty(); - - private RuntimeBinding( - String key, - IrisImageMapApplication application, - CompiledIrisImageMap compiled, - Map regions, - Map biomes, - Map blocks, - List maskDefinitions - ) { - this.key = key; - this.application = application; - this.compiled = compiled; - this.regions = regions; - this.biomes = biomes; - this.blocks = blocks; - this.maskDefinitions = maskDefinitions; - } - - private double maskWeight(double worldX, double worldZ) { - return masks.sample(worldX, worldZ); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveObjectPlacementTransaction.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveObjectPlacementTransaction.java deleted file mode 100644 index b8af13f46..000000000 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveObjectPlacementTransaction.java +++ /dev/null @@ -1,286 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.mantle.components; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.volmlib.util.cache.CacheKey; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.placement.IObjectPlacer; -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.collection.KList; -import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; -import org.jetbrains.annotations.Nullable; - -import java.util.HashMap; -import java.util.Map; - -public final class CaveObjectPlacementTransaction implements IObjectPlacer { - private static final int CACHE_MISS = Integer.MIN_VALUE; - - private final IObjectPlacer delegate; - private final Engine engine; - private final int anchorY; - private final int minDepthBelowSurface; - private final int worldHeight; - private final KList mutations; - private final Map bufferedBlocks; - private final Long2IntOpenHashMap surfaceHeights; - private final Long2IntOpenHashMap caveCeilings; - private int blockWrites; - - public CaveObjectPlacementTransaction(IObjectPlacer delegate, int anchorY, int minDepthBelowSurface) { - this.delegate = delegate; - this.engine = delegate.getEngine(); - this.anchorY = anchorY; - this.minDepthBelowSurface = Math.max(0, minDepthBelowSurface); - this.worldHeight = engine == null ? 0 : engine.getHeight(); - this.mutations = new KList<>(); - this.bufferedBlocks = new HashMap<>(); - this.surfaceHeights = new Long2IntOpenHashMap(); - this.caveCeilings = new Long2IntOpenHashMap(); - this.surfaceHeights.defaultReturnValue(CACHE_MISS); - this.caveCeilings.defaultReturnValue(CACHE_MISS); - } - - public CommitResult commit() { - if (blockWrites == 0) { - discard(); - return CommitResult.EMPTY; - } - - for (BufferedMutation mutation : mutations) { - if (!isWithinBounds(mutation.x(), mutation.y(), mutation.z())) { - discard(); - return CommitResult.REJECTED_BOUNDS; - } - } - - for (BufferedMutation mutation : mutations) { - mutation.apply(delegate); - } - discard(); - return CommitResult.COMMITTED; - } - - public void discard() { - mutations.clear(); - bufferedBlocks.clear(); - blockWrites = 0; - } - - public int getCaveCeiling(int x, int z) { - long key = CacheKey.key(x, z); - int cached = caveCeilings.get(key); - if (cached != CACHE_MISS) { - return cached; - } - - int ceiling = findCaveCeiling(x, z); - caveCeilings.put(key, ceiling); - return ceiling; - } - - static int maxBuriedY(int worldHeight, int surfaceY, int minDepthBelowSurface) { - return Math.min(worldHeight - 1, surfaceY - Math.max(0, minDepthBelowSurface)); - } - - @Override - public int getHighest(int x, int z, IrisData data) { - return delegate.getHighest(x, z, data); - } - - @Override - public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) { - return delegate.getHighest(x, z, data, ignoreFluid); - } - - @Override - public void set(int x, int y, int z, PlatformBlockState state) { - if (state == null) { - return; - } - mutations.add(new BlockMutation(x, y, z, state)); - bufferedBlocks.put(new PositionKey(x, y, z), state); - blockWrites++; - } - - @Override - public PlatformBlockState get(int x, int y, int z) { - PlatformBlockState buffered = bufferedBlocks.get(new PositionKey(x, y, z)); - return buffered == null ? delegate.get(x, y, z) : buffered; - } - - @Override - public boolean isPreventingDecay() { - return delegate.isPreventingDecay(); - } - - @Override - public boolean isCarved(int x, int y, int z) { - return delegate.isCarved(x, y, z); - } - - @Override - public boolean isSurfaceSolid(int x, int y, int z) { - return delegate.isSurfaceSolid(x, y, z); - } - - @Override - public boolean isSolid(int x, int y, int z) { - PlatformBlockState buffered = bufferedBlocks.get(new PositionKey(x, y, z)); - return buffered == null ? delegate.isSolid(x, y, z) : B.isSolid(buffered); - } - - @Override - public boolean isUnderwater(int x, int z) { - return delegate.isUnderwater(x, z); - } - - @Override - public int getFluidHeight() { - return delegate.getFluidHeight(); - } - - @Override - public boolean isDebugSmartBore() { - return delegate.isDebugSmartBore(); - } - - @Override - public void setTile(int x, int y, int z, TileData tile) { - if (tile != null) { - mutations.add(new TileMutation(x, y, z, tile)); - } - } - - @Override - public void setData(int x, int y, int z, T data) { - if (data == null) { - return; - } - mutations.add(new DataMutation(x, y, z, data)); - if (data instanceof PlatformBlockState state) { - bufferedBlocks.put(new PositionKey(x, y, z), state); - blockWrites++; - } - } - - @Override - public @Nullable T getData(int x, int y, int z, Class type) { - for (int i = mutations.size() - 1; i >= 0; i--) { - BufferedMutation mutation = mutations.get(i); - if (mutation.x() != x || mutation.y() != y || mutation.z() != z) { - continue; - } - Object value = mutation.value(); - if (type.isInstance(value)) { - return type.cast(value); - } - } - return delegate.getData(x, y, z, type); - } - - @Override - public Engine getEngine() { - return engine; - } - - private boolean isWithinBounds(int x, int y, int z) { - if (engine == null || y < 0 || y >= worldHeight) { - return false; - } - int surfaceY = getSurfaceHeight(x, z); - if (y > maxBuriedY(worldHeight, surfaceY, minDepthBelowSurface)) { - return false; - } - return y < getCaveCeiling(x, z); - } - - private int getSurfaceHeight(int x, int z) { - long key = CacheKey.key(x, z); - int cached = surfaceHeights.get(key); - if (cached != CACHE_MISS) { - return cached; - } - int surfaceY = engine.getHeight(x, z, true); - surfaceHeights.put(key, surfaceY); - return surfaceY; - } - - private int findCaveCeiling(int x, int z) { - if (worldHeight <= 0 || anchorY < 0 || anchorY >= worldHeight) { - return 0; - } - if (!delegate.isCarved(x, anchorY, z)) { - return Math.min(worldHeight, anchorY + 1); - } - - int scanLimit = Math.min(worldHeight - 1, Math.max(anchorY, getSurfaceHeight(x, z))); - for (int y = anchorY + 1; y <= scanLimit; y++) { - if (!delegate.isCarved(x, y, z)) { - return y; - } - } - return Math.min(worldHeight, scanLimit + 1); - } - - public enum CommitResult { - COMMITTED, - EMPTY, - REJECTED_BOUNDS - } - - private interface BufferedMutation { - int x(); - - int y(); - - int z(); - - Object value(); - - void apply(IObjectPlacer placer); - } - - private record BlockMutation(int x, int y, int z, PlatformBlockState value) implements BufferedMutation { - @Override - public void apply(IObjectPlacer placer) { - placer.set(x, y, z, value); - } - } - - private record TileMutation(int x, int y, int z, TileData value) implements BufferedMutation { - @Override - public void apply(IObjectPlacer placer) { - placer.setTile(x, y, z, value); - } - } - - private record DataMutation(int x, int y, int z, Object value) implements BufferedMutation { - @Override - public void apply(IObjectPlacer placer) { - placer.setData(x, y, z, value); - } - } - - private record PositionKey(int x, int y, int z) { - } -} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacementTransaction.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacementTransaction.java deleted file mode 100644 index c88f54e1c..000000000 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacementTransaction.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.mantle.components; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.placement.IObjectPlacer; -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.collection.KList; -import org.jetbrains.annotations.Nullable; - -import java.util.HashMap; -import java.util.Map; - -public final class FloatingObjectPlacementTransaction implements IObjectPlacer { - private final IslandAnchorPlacer delegate; - private final KList mutations; - private final Map bufferedBlocks; - private int blockWrites; - - public FloatingObjectPlacementTransaction(IslandAnchorPlacer delegate) { - this.delegate = delegate; - this.mutations = new KList<>(); - this.bufferedBlocks = new HashMap<>(); - } - - public CommitResult commit() { - if (blockWrites == 0) { - discard(); - return CommitResult.EMPTY; - } - for (BufferedMutation mutation : mutations) { - if (!delegate.canWriteObjectBlock(mutation.x(), mutation.y(), mutation.z())) { - discard(); - return CommitResult.REJECTED_SUPPORT; - } - } - for (BufferedMutation mutation : mutations) { - mutation.apply(delegate); - } - discard(); - return CommitResult.COMMITTED; - } - - public void discard() { - mutations.clear(); - bufferedBlocks.clear(); - blockWrites = 0; - } - - @Override - public int getHighest(int x, int z, IrisData data) { - return delegate.getHighest(x, z, data); - } - - @Override - public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) { - return delegate.getHighest(x, z, data, ignoreFluid); - } - - @Override - public void set(int x, int y, int z, PlatformBlockState state) { - if (state == null) { - return; - } - mutations.add(new BlockMutation(x, y, z, state)); - bufferedBlocks.put(new PositionKey(x, y, z), state); - blockWrites++; - } - - @Override - public PlatformBlockState get(int x, int y, int z) { - PlatformBlockState state = bufferedBlocks.get(new PositionKey(x, y, z)); - return state == null ? delegate.get(x, y, z) : state; - } - - @Override - public boolean isPreventingDecay() { - return delegate.isPreventingDecay(); - } - - @Override - public boolean isCarved(int x, int y, int z) { - return delegate.isCarved(x, y, z); - } - - @Override - public boolean isSurfaceSolid(int x, int y, int z) { - return delegate.isSurfaceSolid(x, y, z); - } - - @Override - public boolean isSolid(int x, int y, int z) { - PlatformBlockState state = bufferedBlocks.get(new PositionKey(x, y, z)); - return state == null ? delegate.isSolid(x, y, z) : B.isSolid(state); - } - - @Override - public boolean isUnderwater(int x, int z) { - return delegate.isUnderwater(x, z); - } - - @Override - public int getFluidHeight() { - return delegate.getFluidHeight(); - } - - @Override - public boolean isDebugSmartBore() { - return delegate.isDebugSmartBore(); - } - - @Override - public void setTile(int x, int y, int z, TileData tile) { - if (tile != null) { - mutations.add(new TileMutation(x, y, z, tile)); - } - } - - @Override - public void setData(int x, int y, int z, T data) { - if (data == null) { - return; - } - mutations.add(new DataMutation(x, y, z, data)); - if (data instanceof PlatformBlockState state) { - bufferedBlocks.put(new PositionKey(x, y, z), state); - blockWrites++; - } - } - - @Override - public @Nullable T getData(int x, int y, int z, Class type) { - for (int i = mutations.size() - 1; i >= 0; i--) { - BufferedMutation mutation = mutations.get(i); - if (mutation.x() != x || mutation.y() != y || mutation.z() != z) { - continue; - } - Object value = mutation.value(); - if (type.isInstance(value)) { - return type.cast(value); - } - } - return delegate.getData(x, y, z, type); - } - - @Override - public Engine getEngine() { - return delegate.getEngine(); - } - - public enum CommitResult { - COMMITTED, - EMPTY, - REJECTED_SUPPORT - } - - private interface BufferedMutation { - int x(); - - int y(); - - int z(); - - Object value(); - - void apply(IObjectPlacer placer); - } - - private record BlockMutation(int x, int y, int z, PlatformBlockState value) implements BufferedMutation { - @Override - public void apply(IObjectPlacer placer) { - placer.set(x, y, z, value); - } - } - - private record TileMutation(int x, int y, int z, TileData value) implements BufferedMutation { - @Override - public void apply(IObjectPlacer placer) { - placer.setTile(x, y, z, value); - } - } - - private record DataMutation(int x, int y, int z, Object value) implements BufferedMutation { - @Override - public void apply(IObjectPlacer placer) { - placer.setData(x, y, z, value); - } - } - - private record PositionKey(int x, int y, int z) { - } -} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugObjectPlacer.java b/src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugObjectPlacer.java deleted file mode 100644 index d2a958e68..000000000 --- a/src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugObjectPlacer.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.mantle.components; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.placement.IObjectPlacer; -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.spi.PlatformBlockState; -import com.volmit.ModuleLog; - -public final class GoldenDebugObjectPlacer implements IObjectPlacer { - private static final int[] GOLDEN_DEBUG_TARGET = parseGoldenDebugTarget(resolveGoldenDebugSpec()); - private static final boolean GOLDEN_DEBUG = GOLDEN_DEBUG_TARGET != null; - - private final IObjectPlacer delegate; - private final String tag; - private final ModuleLog log; - - public GoldenDebugObjectPlacer(IObjectPlacer delegate, String tag, ModuleLog log) { - this.delegate = delegate; - this.tag = tag; - this.log = log; - } - - private static String resolveGoldenDebugSpec() { - String property = System.getProperty("iris.goldendebug"); - if (property != null && !property.isBlank()) { - return property; - } - try { - java.io.File marker = new java.io.File("plugins/Iris/goldendebug.txt"); - if (marker.isFile()) { - return java.nio.file.Files.readString(marker.toPath()).trim(); - } - } catch (Throwable ignored) { - } - return null; - } - - private static int[] parseGoldenDebugTarget(String raw) { - if (raw == null || raw.isBlank()) { - return null; - } - String[] parts = raw.split(","); - if (parts.length != 2 && parts.length != 3) { - return null; - } - try { - int radius = parts.length == 3 ? Integer.parseInt(parts[2].trim()) : 0; - return new int[]{Integer.parseInt(parts[0].trim()), Integer.parseInt(parts[1].trim()), radius}; - } catch (NumberFormatException e) { - return null; - } - } - - public static boolean isGoldenDebugChunk(int x, int z) { - return GOLDEN_DEBUG - && Math.abs(GOLDEN_DEBUG_TARGET[0] - x) <= GOLDEN_DEBUG_TARGET[2] - && Math.abs(GOLDEN_DEBUG_TARGET[1] - z) <= GOLDEN_DEBUG_TARGET[2]; - } - - @Override - public int getHighest(int x, int z, IrisData data) { - int result = delegate.getHighest(x, z, data); - log.debug("Goldendebug query: tag=" + tag + " getHighest(" + x + "," + z + ")=" + result); - return result; - } - - @Override - public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) { - int result = delegate.getHighest(x, z, data, ignoreFluid); - log.debug("Goldendebug query: tag=" + tag + " getHighest(" + x + "," + z + ",ignoreFluid=" + ignoreFluid + ")=" + result); - return result; - } - - @Override - public void set(int x, int y, int z, PlatformBlockState d) { - delegate.set(x, y, z, d); - } - - @Override - public PlatformBlockState get(int x, int y, int z) { - return delegate.get(x, y, z); - } - - @Override - public boolean isPreventingDecay() { - return delegate.isPreventingDecay(); - } - - @Override - public boolean isCarved(int x, int y, int z) { - boolean result = delegate.isCarved(x, y, z); - log.debug("Goldendebug query: tag=" + tag + " isCarved(" + x + "," + y + "," + z + ")=" + result); - return result; - } - - @Override - public boolean isSurfaceSolid(int x, int y, int z) { - return delegate.isSurfaceSolid(x, y, z); - } - - @Override - public boolean isSolid(int x, int y, int z) { - boolean result = delegate.isSolid(x, y, z); - log.debug("Goldendebug query: tag=" + tag + " isSolid(" + x + "," + y + "," + z + ")=" + result); - return result; - } - - @Override - public boolean isUnderwater(int x, int z) { - return delegate.isUnderwater(x, z); - } - - @Override - public int getFluidHeight() { - return delegate.getFluidHeight(); - } - - @Override - public boolean isDebugSmartBore() { - return delegate.isDebugSmartBore(); - } - - @Override - public void setData(int xx, int yy, int zz, T data) { - delegate.setData(xx, yy, zz, data); - } - - @Override - public T getData(int xx, int yy, int zz, Class t) { - return delegate.getData(xx, yy, zz, t); - } - - @Override - public void setTile(int xx, int yy, int zz, TileData tile) { - delegate.setTile(xx, yy, zz, tile); - } - - @Override - public Engine getEngine() { - return delegate.getEngine(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/IslandAnchorPlacer.java b/src/main/java/art/arcane/iris/engine/mantle/components/IslandAnchorPlacer.java deleted file mode 100644 index 9be265fe0..000000000 --- a/src/main/java/art/arcane/iris/engine/mantle/components/IslandAnchorPlacer.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.mantle.components; - -import art.arcane.iris.builtin.floating.IslandAnchor; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.mantle.MantleWriter; -import art.arcane.iris.engine.object.placement.IObjectPlacer; -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.spi.PlatformBlockState; -import org.jetbrains.annotations.Nullable; - -/** - * Iris's placer for an object placed against a floating island: heights and the island's solid blocks come from the - * {@link IslandAnchor} the floating module samples, and a block is written only where the anchor lets the object write. - * Everything else is the mantle's. - */ -public final class IslandAnchorPlacer implements IObjectPlacer { - private final MantleWriter wrapped; - private final IslandAnchor anchor; - - public IslandAnchorPlacer(MantleWriter wrapped, IslandAnchor anchor) { - this.wrapped = wrapped; - this.anchor = anchor; - } - - public boolean canWriteObjectBlock(int x, int y, int z) { - return anchor.writes(x, y, z); - } - - @Override - public int getHighest(int x, int z, IrisData data) { - return anchor.faceY(x, z); - } - - @Override - public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) { - return getHighest(x, z, data); - } - - @Override - public boolean isUnderwater(int x, int z) { - return false; - } - - @Override - public boolean isSolid(int x, int y, int z) { - return anchor.hasIsland(x, z) ? anchor.islandSolid(x, y, z) : wrapped.isSolid(x, y, z); - } - - @Override - public boolean isCarved(int x, int y, int z) { - return wrapped.isCarved(x, y, z); - } - - @Override - public boolean isSurfaceSolid(int x, int y, int z) { - return wrapped.isSurfaceSolid(x, y, z); - } - - @Override - public void set(int x, int y, int z, PlatformBlockState state) { - if (anchor.writes(x, y, z)) { - wrapped.set(x, y, z, state); - } - } - - @Override - public PlatformBlockState get(int x, int y, int z) { - return wrapped.get(x, y, z); - } - - @Override - public boolean isPreventingDecay() { - return wrapped.isPreventingDecay(); - } - - @Override - public int getFluidHeight() { - return wrapped.getFluidHeight(); - } - - @Override - public boolean isDebugSmartBore() { - return wrapped.isDebugSmartBore(); - } - - @Override - public void setTile(int x, int y, int z, TileData tile) { - if (anchor.writes(x, y, z)) { - wrapped.setTile(x, y, z, tile); - } - } - - @Override - public void setData(int x, int y, int z, T data) { - if (anchor.writes(x, y, z)) { - wrapped.setData(x, y, z, data); - } - } - - @Override - public @Nullable T getData(int x, int y, int z, Class type) { - return wrapped.getData(x, y, z, type); - } - - @Override - public Engine getEngine() { - return wrapped == null ? null : wrapped.getEngine(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java deleted file mode 100644 index a33ed27ec..000000000 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.mantle.components; - -import art.arcane.iris.builtin.structure.StructureCarveShape; -import art.arcane.iris.util.project.noise.CNG; - -/** - * Carve envelope math shared by the Iris-assembled structure path and the native (vanilla template) - * structure path so both shrinkwrap a structure footprint the same way. The lobe channel and the - * eroded floor are only sampled by the native path; the Iris-assembled path still carves a uniform - * side reach and a uniform floor cut. - */ -public final class StructureCarveEnvelope { - private static final double CEILING_LOBE_RATIO = 0.5D; - private static final double CEILING_ROLL_FREQUENCY_RATIO = 3D / 7D; - private static final double FLOOR_ROLL_AMPLITUDE = 0.35D; - private static final double FLOOR_ROLL_FREQUENCY_RATIO = 5D / 11D; - // Maps a lobe frequency onto the smooth 2D channel so the auto-derived 0.015 lands near a - // 40 block wavelength: wide enough that walls bulge and recede instead of tracking the footprint. - private static final double LOBE_FREQUENCY_SCALE = 256D; - - private StructureCarveEnvelope() { - } - - /** - * Per-column horizontal carve reach. The lobe channel only ever removes padding, so the boundary - * stays inside the footprint bounds the carve was sized against and never falls below - * {@code horizontalPadding * (1 - lobeStrength)}. - */ - public static double lobedSideReach(CNG lobe, double lobeFrequency, double lobeStrength, - int x, int z, int horizontalPadding) { - if (horizontalPadding <= 0) { - return 0D; - } - return horizontalPadding * lobeFactor(lobe, lobeFrequency, lobeStrength, x, z); - } - - /** - * Ceiling counterpart of {@link #lobedSideReach}, deliberately half as strong so the roof swells - * with the same lobes without collapsing onto the pieces. - */ - public static double lobedUpReach(CNG lobe, double lobeFrequency, double lobeStrength, - int x, int z, double upReach) { - if (upReach <= 0D) { - return upReach; - } - return Math.max(1D, upReach - * lobeFactor(lobe, lobeFrequency, lobeStrength * CEILING_LOBE_RATIO, x, z)); - } - - private static double lobeFactor(CNG lobe, double lobeFrequency, double lobeStrength, - int x, int z) { - double clampedStrength = Math.max(0D, Math.min(1D, lobeStrength)); - if (lobe == null || clampedStrength <= 0D) { - return 1D; - } - double scaledFrequency = lobeFrequency * LOBE_FREQUENCY_SCALE; - double sample = Math.max(0D, Math.min(1D, lobe.fitDouble( - 0D, 1D, x * scaledFrequency, z * scaledFrequency))); - return 1D - clampedStrength * (1D - sample); - } - - public static double erodedUpReach(CNG roll, double frequency, double strength, int x, int z, int head) { - if (head <= 0) { - return 0D; - } - double clampedStrength = Math.max(0D, Math.min(1D, strength)); - if (clampedStrength <= 0D) { - return Math.max(1D, head); - } - double rollFrequency = frequency * CEILING_ROLL_FREQUENCY_RATIO; - double sample = roll.fitDouble(0D, 1D, x * rollFrequency, z * rollFrequency) * 0.7D - + roll.fitDouble(0D, 1D, x * rollFrequency * 3D, z * rollFrequency * 3D) * 0.3D; - double contrast = Math.max(0D, Math.min(1D, (sample - 0.5D) * 2.6D + 0.5D)); - double roundedReach = Math.max(1D, head); - double erodedReach = Math.max(1D, head * (0.4D + 1.4D * contrast)); - return roundedReach + clampedStrength * (erodedReach - roundedReach); - } - - /** - * Floor counterpart of {@link #erodedUpReach}. The amplitude is deliberately small and the result - * never exceeds the configured floor padding, so a padding of zero leaves every column standing on - * its own supporting block instead of undermining the structure. - */ - public static double erodedDownReach(CNG roll, double frequency, double strength, int x, int z, int floorCut) { - if (floorCut <= 0) { - return 0D; - } - double clampedStrength = Math.max(0D, Math.min(1D, strength)); - if (clampedStrength <= 0D) { - return floorCut; - } - double rollFrequency = frequency * FLOOR_ROLL_FREQUENCY_RATIO; - double sample = roll.fitDouble(0D, 1D, x * rollFrequency, z * rollFrequency); - return floorCut * (1D - clampedStrength * FLOOR_ROLL_AMPLITUDE * (1D - sample)); - } - - public static double normalizedVerticalDistance(int y, int sourceMinY, int sourceMaxY, - double upReach, double downReach) { - if (y > sourceMaxY) { - return (y - sourceMaxY) / upReach; - } - if (y < sourceMinY) { - return (sourceMinY - y) / downReach; - } - return 0D; - } - - public static double overboreBoundaryLimit(double noise, double strength) { - double clampedNoise = Math.max(0.0, Math.min(1.0, noise)); - double clampedStrength = Math.max(0.0, Math.min(1.0, strength)); - return 1D - clampedStrength * (1D - clampedNoise); - } - - public static boolean shouldCarveOverboreCell(StructureCarveShape shape, double distanceSquared, - double noise, double strength) { - if (distanceSquared <= 0.0) { - return true; - } - StructureCarveShape resolvedShape = shape == null ? StructureCarveShape.ERODED : shape; - return switch (resolvedShape) { - case BOX -> true; - case ROUNDED -> distanceSquared <= 1D; - case ERODED -> { - double limit = overboreBoundaryLimit(noise, strength); - yield distanceSquared <= 1D && distanceSquared <= limit * limit; - } - }; - } -} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarvingFootprint.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarvingFootprint.java deleted file mode 100644 index 119a963c1..000000000 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarvingFootprint.java +++ /dev/null @@ -1,456 +0,0 @@ -package art.arcane.iris.engine.mantle.components; - -import art.arcane.iris.engine.framework.PlacedStructurePiece; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectRotation; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.math.IrisBlockVector; -import art.arcane.volmlib.util.collection.KList; -import it.unimi.dsi.fastutil.longs.Long2LongMap; -import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap; - -import java.util.Arrays; - -public final class StructureCarvingFootprint { - static final int DEFAULT_MAX_CELLS = 1_048_576; - - private final int minX; - private final int maxX; - private final int minZ; - private final int maxZ; - private final int width; - private final int depth; - private final long[] distanceSquared; - private final int[] nearestSourceIds; - private final int[] sourceMinY; - private final int[] sourceMaxY; - - private StructureCarvingFootprint(FootprintData data) { - minX = data.minX(); - maxX = data.maxX(); - minZ = data.minZ(); - maxZ = data.maxZ(); - width = data.width(); - depth = data.depth(); - distanceSquared = data.distanceSquared(); - nearestSourceIds = data.nearestSourceIds(); - sourceMinY = data.sourceMinY(); - sourceMaxY = data.sourceMaxY(); - } - - static StructureCarvingFootprint from(KList pieces, int padding) { - return from(pieces, padding, DEFAULT_MAX_CELLS); - } - - static StructureCarvingFootprint from(KList pieces, int padding, int maxCells) { - return fromColumns(sink -> emitPieceColumns(pieces, sink), padding, maxCells); - } - - /** - * Builds a footprint from any per-column occupancy source. The source reports one contribution per - * occupied column; overlapping contributions merge into a single column whose vertical extents span - * every contribution. - */ - public static StructureCarvingFootprint fromColumns(ColumnSource source, int padding, int maxCells) { - if (padding < 0) { - throw new IllegalArgumentException("padding must be non-negative"); - } - if (maxCells < 1) { - throw new IllegalArgumentException("maxCells must be positive"); - } - if (source == null) { - return null; - } - - SourceCollection sources = collectSources(source); - if (sources == null || sources.columns().isEmpty()) { - return null; - } - - Bounds bounds = paddedBounds(sources.bounds(), padding, maxCells); - if (bounds == null) { - return null; - } - - int[] nearestSourceIds = new int[bounds.cellCount()]; - Arrays.fill(nearestSourceIds, -1); - int sourceCount = sources.columns().size(); - int[] sourceX = new int[sourceCount]; - int[] sourceZ = new int[sourceCount]; - int[] sourceMinY = new int[sourceCount]; - int[] sourceMaxY = new int[sourceCount]; - int sourceId = 0; - for (Long2LongMap.Entry entry : sources.columns().long2LongEntrySet()) { - int localX = unpackX(entry.getLongKey()) - bounds.minX(); - int localZ = unpackZ(entry.getLongKey()) - bounds.minZ(); - long heights = entry.getLongValue(); - sourceX[sourceId] = localX; - sourceZ[sourceId] = localZ; - sourceMinY[sourceId] = unpackMinY(heights); - sourceMaxY[sourceId] = unpackMaxY(heights); - nearestSourceIds[localZ * bounds.width() + localX] = sourceId; - sourceId++; - } - - transformRows(nearestSourceIds, sourceX, sourceZ, bounds.width(), bounds.depth()); - long[] distanceSquared = transformColumns( - nearestSourceIds, sourceX, sourceZ, bounds.width(), bounds.depth()); - FootprintData data = new FootprintData( - bounds.minX(), bounds.maxX(), bounds.minZ(), bounds.maxZ(), - bounds.width(), bounds.depth(), distanceSquared, nearestSourceIds, - sourceMinY, sourceMaxY); - return new StructureCarvingFootprint(data); - } - - public int minX() { - return minX; - } - - public int maxX() { - return maxX; - } - - public int minZ() { - return minZ; - } - - public int maxZ() { - return maxZ; - } - - public int width() { - return width; - } - - public int depth() { - return depth; - } - - public boolean contains(int worldX, int worldZ) { - return worldX >= minX && worldX <= maxX && worldZ >= minZ && worldZ <= maxZ; - } - - public int indexAt(int worldX, int worldZ) { - if (!contains(worldX, worldZ)) { - return -1; - } - return (worldZ - minZ) * width + worldX - minX; - } - - public long distanceSquaredAt(int worldX, int worldZ) { - return distanceSquaredAt(requireIndex(worldX, worldZ)); - } - - public long distanceSquaredAt(int index) { - return distanceSquared[index]; - } - - public int sourceMinYAt(int worldX, int worldZ) { - return sourceMinYAt(requireIndex(worldX, worldZ)); - } - - public int sourceMinYAt(int index) { - return sourceMinY[nearestSourceIds[index]]; - } - - public int sourceMaxYAt(int worldX, int worldZ) { - return sourceMaxYAt(requireIndex(worldX, worldZ)); - } - - public int sourceMaxYAt(int index) { - return sourceMaxY[nearestSourceIds[index]]; - } - - Column sample(int worldX, int worldZ) { - int index = indexAt(worldX, worldZ); - if (index < 0) { - return null; - } - return new Column(distanceSquaredAt(index), sourceMinYAt(index), sourceMaxYAt(index)); - } - - private static SourceCollection collectSources(ColumnSource source) { - Long2LongOpenHashMap columns = new Long2LongOpenHashMap(); - MutableBounds bounds = new MutableBounds(); - boolean usable = source.emit((worldX, worldZ, minY, maxY) -> { - mergeColumn(columns, worldX, worldZ, minY, maxY); - bounds.include(worldX, worldZ); - }); - if (!usable) { - return null; - } - return columns.isEmpty() ? null : new SourceCollection(columns, bounds.freeze()); - } - - private static boolean emitPieceColumns(KList pieces, ColumnSink sink) { - if (pieces == null) { - return true; - } - for (PlacedStructurePiece piece : pieces) { - if (piece == null) { - continue; - } - IrisObject object = piece.getObject(); - IrisObjectRotation rotation = piece.getRotation(); - if (object == null || rotation == null || object.getBlocks() == null) { - continue; - } - for (IrisBlockVector local : object.getBlocks().keys()) { - if (local == null || B.isAir(object.getBlocks().get(local))) { - continue; - } - IrisBlockVector rotated = rotation.rotate(local.clone()); - long worldX = (long) piece.getX() + rotated.getBlockX(); - long worldY = (long) piece.getY() + rotated.getBlockY(); - long worldZ = (long) piece.getZ() + rotated.getBlockZ(); - if (!fitsInteger(worldX) || !fitsInteger(worldY) || !fitsInteger(worldZ)) { - return false; - } - sink.column((int) worldX, (int) worldZ, (int) worldY, (int) worldY); - } - } - return true; - } - - private static Bounds paddedBounds(MutableBoundsSnapshot sourceBounds, int padding, int maxCells) { - long paddedMinX = (long) sourceBounds.minX() - padding; - long paddedMaxX = (long) sourceBounds.maxX() + padding; - long paddedMinZ = (long) sourceBounds.minZ() - padding; - long paddedMaxZ = (long) sourceBounds.maxZ() + padding; - if (!fitsInteger(paddedMinX) || !fitsInteger(paddedMaxX) - || !fitsInteger(paddedMinZ) || !fitsInteger(paddedMaxZ)) { - return null; - } - long width = paddedMaxX - paddedMinX + 1L; - long depth = paddedMaxZ - paddedMinZ + 1L; - if (width < 1L || depth < 1L || width > Integer.MAX_VALUE || depth > Integer.MAX_VALUE - || width > maxCells / depth) { - return null; - } - int cellCount = (int) (width * depth); - return new Bounds( - (int) paddedMinX, (int) paddedMaxX, (int) paddedMinZ, (int) paddedMaxZ, - (int) width, (int) depth, cellCount); - } - - private static void mergeColumn(Long2LongOpenHashMap columns, int x, int z, int minY, int maxY) { - long key = pack(x, z); - if (!columns.containsKey(key)) { - columns.put(key, packHeights(minY, maxY)); - return; - } - long existing = columns.get(key); - columns.put(key, packHeights( - Math.min(minY, unpackMinY(existing)), Math.max(maxY, unpackMaxY(existing)))); - } - - private static void transformRows(int[] nearestSourceIds, int[] sourceX, int[] sourceZ, - int width, int depth) { - for (int z = 0; z < depth; z++) { - int rowStart = z * width; - int previousSource = -1; - for (int x = 0; x < width; x++) { - int index = rowStart + x; - int sourceId = nearestSourceIds[index]; - if (isExplicitSource(sourceId, x, z, sourceX, sourceZ)) { - previousSource = sourceId; - } else { - nearestSourceIds[index] = previousSource; - } - } - int nextSource = -1; - for (int x = width - 1; x >= 0; x--) { - int index = rowStart + x; - int currentSource = nearestSourceIds[index]; - if (isExplicitSource(currentSource, x, z, sourceX, sourceZ)) { - nextSource = currentSource; - } - if (isBetterHorizontalSource(nextSource, currentSource, x, sourceX)) { - nearestSourceIds[index] = nextSource; - } - } - } - } - - private static long[] transformColumns(int[] nearestSourceIds, int[] sourceX, int[] sourceZ, - int width, int depth) { - long[] distanceSquared = new long[nearestSourceIds.length]; - int[] siteRows = new int[depth]; - int[] siteSourceIds = new int[depth]; - int[] starts = new int[depth]; - long[] siteCosts = new long[depth]; - for (int x = 0; x < width; x++) { - int siteCount = buildEnvelope( - nearestSourceIds, sourceX, width, depth, x, - siteRows, siteSourceIds, starts, siteCosts); - int siteIndex = 0; - for (int z = 0; z < depth; z++) { - while (siteIndex + 1 < siteCount && starts[siteIndex + 1] <= z) { - siteIndex++; - } - int sourceId = siteSourceIds[siteIndex]; - int index = z * width + x; - long deltaX = (long) x - sourceX[sourceId]; - long deltaZ = (long) z - sourceZ[sourceId]; - nearestSourceIds[index] = sourceId; - distanceSquared[index] = deltaX * deltaX + deltaZ * deltaZ; - } - } - return distanceSquared; - } - - private static int buildEnvelope(int[] nearestSourceIds, int[] sourceX, int width, int depth, - int x, int[] siteRows, int[] siteSourceIds, - int[] starts, long[] siteCosts) { - int siteCount = 0; - for (int z = 0; z < depth; z++) { - int sourceId = nearestSourceIds[z * width + x]; - if (sourceId < 0) { - continue; - } - long deltaX = (long) x - sourceX[sourceId]; - long cost = deltaX * deltaX; - int start = Integer.MIN_VALUE; - while (siteCount > 0) { - start = firstStrictlyBetterAt( - siteRows[siteCount - 1], siteCosts[siteCount - 1], z, cost); - if (start > starts[siteCount - 1]) { - break; - } - siteCount--; - } - if (siteCount == 0) { - start = Integer.MIN_VALUE; - } - siteRows[siteCount] = z; - siteSourceIds[siteCount] = sourceId; - siteCosts[siteCount] = cost; - starts[siteCount] = start; - siteCount++; - } - return siteCount; - } - - private static int firstStrictlyBetterAt(int existingRow, long existingCost, - int candidateRow, long candidateCost) { - long numerator = candidateCost + (long) candidateRow * candidateRow - - existingCost - (long) existingRow * existingRow; - long denominator = 2L * (candidateRow - existingRow); - long start = Math.floorDiv(numerator, denominator) + 1L; - if (start < Integer.MIN_VALUE) { - return Integer.MIN_VALUE; - } - if (start > Integer.MAX_VALUE) { - return Integer.MAX_VALUE; - } - return (int) start; - } - - private static boolean isExplicitSource(int sourceId, int x, int z, - int[] sourceX, int[] sourceZ) { - return sourceId >= 0 && sourceX[sourceId] == x && sourceZ[sourceId] == z; - } - - private static boolean isBetterHorizontalSource(int candidateId, int currentId, - int x, int[] sourceX) { - if (candidateId < 0) { - return false; - } - if (currentId < 0) { - return true; - } - long candidateDelta = (long) x - sourceX[candidateId]; - long currentDelta = (long) x - sourceX[currentId]; - long candidateDistance = candidateDelta * candidateDelta; - long currentDistance = currentDelta * currentDelta; - return candidateDistance < currentDistance - || candidateDistance == currentDistance && sourceX[candidateId] < sourceX[currentId]; - } - - private int requireIndex(int worldX, int worldZ) { - int index = indexAt(worldX, worldZ); - if (index < 0) { - throw new IndexOutOfBoundsException( - "coordinate outside carving footprint: " + worldX + "," + worldZ); - } - return index; - } - - private static boolean fitsInteger(long value) { - return value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE; - } - - private static long pack(int x, int z) { - return (long) x << 32 | z & 0xffffffffL; - } - - private static int unpackX(long packed) { - return (int) (packed >> 32); - } - - private static int unpackZ(long packed) { - return (int) packed; - } - - private static long packHeights(int minY, int maxY) { - return (long) minY << 32 | maxY & 0xffffffffL; - } - - private static int unpackMinY(long packed) { - return (int) (packed >> 32); - } - - private static int unpackMaxY(long packed) { - return (int) packed; - } - - @FunctionalInterface - public interface ColumnSink { - void column(int worldX, int worldZ, int minY, int maxY); - } - - @FunctionalInterface - public interface ColumnSource { - /** - * Reports every occupied column to the sink. Returning false abandons the footprint, which is how - * a source rejects occupancy it cannot address (for example coordinates outside the integer range). - */ - boolean emit(ColumnSink sink); - } - - record Column(long distanceSquared, int sourceMinY, int sourceMaxY) { - } - - private record Bounds(int minX, int maxX, int minZ, int maxZ, - int width, int depth, int cellCount) { - } - - private record FootprintData(int minX, int maxX, int minZ, int maxZ, - int width, int depth, long[] distanceSquared, - int[] nearestSourceIds, int[] sourceMinY, int[] sourceMaxY) { - } - - private record SourceCollection(Long2LongOpenHashMap columns, MutableBoundsSnapshot bounds) { - } - - private record MutableBoundsSnapshot(int minX, int maxX, int minZ, int maxZ) { - } - - private static final class MutableBounds { - private int minX = Integer.MAX_VALUE; - private int maxX = Integer.MIN_VALUE; - private int minZ = Integer.MAX_VALUE; - private int maxZ = Integer.MIN_VALUE; - - private void include(int x, int z) { - minX = Math.min(minX, x); - maxX = Math.max(maxX, x); - minZ = Math.min(minZ, z); - maxZ = Math.max(maxZ, z); - } - - private MutableBoundsSnapshot freeze() { - return new MutableBoundsSnapshot(minX, maxX, minZ, maxZ); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlanner.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlanner.java deleted file mode 100644 index 3ac2c9737..000000000 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlanner.java +++ /dev/null @@ -1,79 +0,0 @@ -package art.arcane.iris.engine.mantle.components; - -import art.arcane.iris.spi.PlatformBlockState; -import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; - -import java.util.function.IntConsumer; -import java.util.function.IntPredicate; - -final class StructureFoundationPlanner { - static final int NO_GROUND = Integer.MIN_VALUE; - - private StructureFoundationPlanner() { - } - - static void recordBaseCell(Long2IntOpenHashMap columns, int x, int y, int z, - PlatformBlockState state, boolean supportNonOccluding) { - if (columns == null || state == null - || !(supportNonOccluding ? state.isSolid() : state.isOccluding())) { - return; - } - long columnKey = pack(x, z); - if (!columns.containsKey(columnKey) || y < columns.get(columnKey)) { - columns.put(columnKey, y); - } - } - - static int findGroundY(int foundationY, int maxDepth, int minimumY, IntPredicate solidAtY) { - if (foundationY <= minimumY) { - return NO_GROUND; - } - long requestedFloor = (long) foundationY - Math.max(1, maxDepth); - int scanFloor = (int) Math.max(minimumY, requestedFloor); - for (int y = foundationY - 1; y >= scanFloor; y--) { - if (solidAtY.test(y)) { - return y; - } - } - return NO_GROUND; - } - - static boolean isGroundSolid(PlatformBlockState overlay, boolean carved, int mantleY, int terrainHeight) { - if (mantleY <= 0) { - return true; - } - if (overlay != null) { - return overlay.isSolid(); - } - return !carved && mantleY <= terrainHeight; - } - - static boolean isSurfaceSupportBoundary(PlatformBlockState overlay, boolean carved, - int mantleY, int terrainHeight) { - return carved || isGroundSolid(overlay, false, mantleY, terrainHeight); - } - - static int fillSupportColumn(int foundationY, int groundY, IntConsumer supportAtY) { - if (groundY == NO_GROUND || groundY >= foundationY - 1) { - return 0; - } - int written = 0; - for (int y = foundationY - 1; y > groundY; y--) { - supportAtY.accept(y); - written++; - } - return written; - } - - static long pack(int x, int z) { - return ((long) x << 32) | (z & 0xffffffffL); - } - - static int unpackX(long packed) { - return (int) (packed >> 32); - } - - static int unpackZ(long packed) { - return (int) packed; - } -} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java deleted file mode 100644 index 06d241f91..000000000 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java +++ /dev/null @@ -1,685 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.mantle.components; - -import art.arcane.iris.builtin.anchor.PlaceTrait; -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.engine.framework.structure.StructureResources; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.core.IrisSettings; -import art.arcane.volmlib.util.cache.CacheKey; -import art.arcane.iris.engine.framework.IrisStructureLocator; -import art.arcane.iris.engine.framework.PlacedStructurePiece; -import art.arcane.iris.engine.framework.StructurePlacementScope; -import art.arcane.iris.builtin.structure.StructurePlacementMarker; -import art.arcane.iris.engine.framework.TreeBlockMaterial; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.mantle.MantleWriter; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.iris.builtin.structure.StructureCarveShape; -import art.arcane.iris.builtin.structure.StructurePlacement; -import art.arcane.iris.builtin.structure.StructureStilts; -import com.volmit.ModuleLog; -import com.volmit.block.PaletteSampler; -import com.volmit.block.PaletteSpec; -import art.arcane.iris.builtin.structure.StructureTerrain; -import art.arcane.iris.builtin.structure.StructureTerrainMode; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.math.IrisBlockVector; -import art.arcane.iris.util.project.matter.TileWrapper; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.iris.util.project.context.ChunkContext; -import art.arcane.volmlib.util.documentation.ChunkCoordinates; -import art.arcane.volmlib.util.mantle.runtime.MantleChunk; -import art.arcane.volmlib.util.matter.Matter; -import art.arcane.volmlib.util.matter.MatterCavern; -import art.arcane.volmlib.util.matter.MatterStructurePOI; -import art.arcane.volmlib.util.math.RNG; -import it.unimi.dsi.fastutil.longs.Long2IntMap; -import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Places the Iris structures of the dimension, its regions and biomes into the mantle for - * {@link StructureModule}: their pieces, foundations, bores and carves, clearing object trees they - * intersect. One per engine runtime. Its reach is the largest structure any placement can produce. - */ -public class StructurePlacing { - private static final MatterCavern CARVE_CAVERN = new MatterCavern(true, "", (byte) 3); - - private final Engine engine; - private final ModuleLog log; - - public StructurePlacing(Engine engine, ModuleLog log) { - this.engine = engine; - this.log = log; - } - - /** Places what originates in the chunk at chunk coordinates {@code x}, {@code z} into {@code writer}. */ - @ChunkCoordinates - public void place(MantleWriter writer, int x, int z, ChunkContext context) { - for (StructurePlacement placement : StructurePlacementScope.placementsAt( - engine, x, z)) { - if (!placement.hasIrisStructures()) { - continue; - } - placeFromPlacement(writer, placement, x, z); - } - } - - @ChunkCoordinates - private void placeFromPlacement(MantleWriter writer, StructurePlacement placement, int cx, int cz) { - IrisStructureLocator.ResolvedPlacement resolved = IrisStructureLocator.resolvePlacement( - engine, placement, cx, cz); - if (resolved == null) { - return; - } - - boolean trace = IrisSettings.get().getGeneral().isDebug(); - if (trace) { - log.debug("[StructTrace] ORIGIN chunk=" + cx + "," + cz + " structures=" + placement.structures() - + " anchor=" + placement.resolvedAnchor() + " band=" + placement.minHeight() + ".." + placement.maxHeight()); - } - - String key = resolved.structureKey(); - IrisStructure structure = resolved.structure(); - KList pieces = resolvedPiecesOrNull(resolved, cx, cz); - if (pieces == null) { - return; - } - RNG rng = resolved.rng(); - int baseY = resolved.baseY(); - if (trace) { - log.debug("[StructTrace] ASSEMBLED chunk=" + cx + "," + cz + " key=" + key + " baseY=" + baseY + " pieces=" + pieces.size()); - } - - if (!placement.isAnchoredUnderground()) { - clearIntersectingObjectTrees(writer, resolved); - } - - StructureTerrain terrain = placement.resolvedTerrain(); - StructureTerrainMode terrainMode = terrain.resolvedMode(); - if (terrainMode == StructureTerrainMode.FORCE_CARVE) { - forceCarveStructure(writer, pieces, terrain); - } else if (terrainMode == StructureTerrainMode.BORE) { - boreStructure(writer, pieces, terrain); - } else if (terrainMode != StructureTerrainMode.PRESERVE - && terrainMode != StructureTerrainMode.SOURCE) { - throw new IllegalStateException("Iris assembly terrain mode " + terrainMode - + " is not implemented for structure '" + key + "'"); - } - - ObjectPlaceMode mode = structure.getPlaceMode(); - int failedPieces = 0; - StructureStilts stilt = placement.stilt().orElse(null); - Long2IntOpenHashMap foundationColumns = stilt == null - ? null : new Long2IntOpenHashMap(); - boolean supportNonOccluding = stilt != null && stilt.supportNonOccluding(); - if (placement.isAnchoredUnderground()) { - ObjectPlaceMode undergroundMode = mode.placeMode().has(PlaceTrait.CAVE_ANCHORED) - ? mode : ObjectPlaceMode.STRUCTURE_PIECE; - for (PlacedStructurePiece p : pieces) { - if (placeObject(writer, structure, p, undergroundMode, p.getY(), rng, - foundationColumns, supportNonOccluding) == -1) { - failedPieces++; - } - } - } else if (mode.placeMode().has(PlaceTrait.FREE_HEIGHT)) { - for (PlacedStructurePiece p : pieces) { - if (placeObject(writer, structure, p, ObjectPlaceMode.STRUCTURE_PIECE, p.getY(), rng, - foundationColumns, supportNonOccluding) == -1) { - failedPieces++; - } - } - } else if (pieces.size() == 1) { - if (placeObject(writer, structure, pieces.getFirst(), mode, -1, rng, - foundationColumns, supportNonOccluding) == -1) { - failedPieces++; - } - } else { - for (PlacedStructurePiece p : pieces) { - if (placeObject(writer, structure, p, ObjectPlaceMode.STRUCTURE_PIECE, p.getY(), rng, - foundationColumns, supportNonOccluding) == -1) { - failedPieces++; - } - } - } - requireAppliedPieces(resolved, cx, cz, failedPieces); - if (failedPieces == 0 && stilt != null) { - placeFoundation(writer, foundationColumns, stilt, rng, !placement.isAnchoredUnderground()); - } - } - - private void placeFoundation(MantleWriter writer, Long2IntOpenHashMap columns, - StructureStilts settings, RNG rng, - boolean surfaceStructure) { - PaletteSpec palette = settings.palette().orElseThrow( - () -> new NullPointerException("Structure stilt palette must not be null")); - PaletteSampler picker = engine.getData().getPackResources().blocks().palette(palette, rng.getSeed()); - int mantleOffset = engine.getMinHeight(); - int maxDepth = Math.max(1, settings.maxDepth()); - for (Long2IntMap.Entry column : columns.long2IntEntrySet()) { - int worldX = StructureFoundationPlanner.unpackX(column.getLongKey()); - int worldZ = StructureFoundationPlanner.unpackZ(column.getLongKey()); - int foundationY = column.getIntValue(); - PlatformBlockState foundationState = writer.getDataIfPresent( - worldX, foundationY, worldZ, PlatformBlockState.class); - if (foundationState == null || !foundationState.isSolid()) { - continue; - } - int terrainHeight = engine.getMantle().trueHeight(worldX, worldZ); - int groundY = StructureFoundationPlanner.findGroundY( - foundationY, maxDepth, 0, - y -> { - PlatformBlockState overlay = writer.getDataIfPresent( - worldX, y, worldZ, PlatformBlockState.class); - boolean carved = writer.getDataIfPresent( - worldX, y, worldZ, MatterCavern.class) != null; - return surfaceStructure - ? StructureFoundationPlanner.isSurfaceSupportBoundary( - overlay, carved, y, terrainHeight) - : StructureFoundationPlanner.isGroundSolid( - overlay, carved, y, terrainHeight); - }); - if (groundY == StructureFoundationPlanner.NO_GROUND) { - continue; - } - StructureFoundationPlanner.fillSupportColumn(foundationY, groundY, y -> { - writeFoundationSupport(writer, picker, worldX, y, worldZ, mantleOffset); - }); - } - } - - /** Writes the stilt palette's block at the column's mantle height, clearing any carve there. */ - static void writeFoundationSupport(MantleWriter writer, PaletteSampler picker, int worldX, int mantleY, int worldZ, - int mantleOffset) { - int worldY = mantleY + mantleOffset; - PlatformBlockState support = B.getState(picker.at(worldX, worldY, worldZ).key()); - if (support == null) { - throw new IllegalStateException("Structure stilt palette resolved no block at " - + worldX + "," + worldY + "," + worldZ); - } - writer.clearData(worldX, mantleY, worldZ, MatterCavern.class); - writer.set(worldX, mantleY, worldZ, support); - } - - static KList resolvedPiecesOrNull( - IrisStructureLocator.ResolvedPlacement resolved, - int chunkX, - int chunkZ - ) { - if (resolved == null) { - return null; - } - KList pieces = resolved.pieces(); - if (!IrisStructureLocator.requirePlacementOutput( - resolved.placement(), resolved.structureKey(), chunkX, chunkZ, - pieces != null && !pieces.isEmpty(), "placement application received no assembled pieces")) { - return null; - } - return pieces; - } - - static void requireAppliedPieces(IrisStructureLocator.ResolvedPlacement resolved, - int chunkX, int chunkZ, int failedPieces) { - IrisStructureLocator.requirePlacementOutput( - resolved.placement(), resolved.structureKey(), chunkX, chunkZ, failedPieces == 0, - "object placement rejected " + failedPieces + " of " + resolved.pieces().size() - + " assembled piece(s)"); - } - - private void boreStructure(MantleWriter writer, KList pieces, - StructureTerrain terrain) { - int[] bounds = computePieceBounds(pieces); - if (bounds == null) { - return; - } - int pad = Math.max(0, terrain.horizontalPadding()); - int minX = bounds[0] - pad; - int minY = bounds[1] - Math.max(0, terrain.floorPadding()); - int minZ = bounds[2] - pad; - int maxX = bounds[3] + pad; - int maxY = bounds[4] + Math.max(0, terrain.ceilingPadding()); - int maxZ = bounds[5] + pad; - int worldMin = engine.getMinHeight() + 1; - int worldMax = engine.getMinHeight() + engine.getHeight() - 1; - minY = Math.max(minY, worldMin); - maxY = Math.min(maxY, worldMax); - if (maxX < minX || maxY < minY || maxZ < minZ) { - return; - } - int mantleOffset = engine.getMinHeight(); - for (int bx = minX; bx <= maxX; bx++) { - for (int by = minY; by <= maxY; by++) { - for (int bz = minZ; bz <= maxZ; bz++) { - writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN); - } - } - } - } - - private void forceCarveStructure(MantleWriter writer, KList pieces, - StructureTerrain terrain) { - int[] bounds = computePieceBounds(pieces); - if (bounds == null) { - return; - } - StructureCarveShape shape = terrain.resolvedShape(); - int margin = Math.max(0, terrain.horizontalPadding()); - int head = Math.max(0, terrain.ceilingPadding()); - int floorCut = Math.max(0, terrain.floorPadding()); - double strength = terrain.resolvedErosionStrength(); - int mantleOffset = engine.getMinHeight(); - int worldMin = engine.getMinHeight() + 1; - int worldMax = engine.getMinHeight() + engine.getHeight() - 1; - int upExtension = shape.maximumCeilingExtension(head, strength); - - if (shape == StructureCarveShape.BOX) { - carveOverboreBox(writer, bounds, margin, head, floorCut, mantleOffset, worldMin, worldMax); - return; - } - - long work = overboreCandidateVolume(bounds, margin, upExtension, floorCut); - StructureCarvingFootprint footprint = StructureCarvingFootprint.from( - pieces, margin, Integer.MAX_VALUE); - if (footprint == null) { - throw new IllegalStateException("Structure force-carve footprint is empty or exceeds addressable memory"); - } - - double frequency = terrain.resolvedErosionFrequency(); - boolean eroded = shape == StructureCarveShape.ERODED && strength > 0D; - CNG blob = null; - CNG roll = null; - if (eroded) { - RNG noiseRng = new RNG(engine.getSeedManager().getMantle() + CacheKey.key(bounds[0], bounds[2])); - blob = CNG.signature(noiseRng); - roll = CNG.signature(noiseRng.nextParallelRNG(0x2A17)); - } - - if (IrisSettings.get().getGeneral().isDebug()) { - log.info("Overbore carving structure cavern: shape=" + shape + " pieces=" + pieces.size() - + " footprint=" + footprint.width() + "x" + footprint.depth() - + " margin=" + margin + " head=" + head + " floorCut=" + floorCut + " work=" + work); - } - - double sideReachSquared = (double) margin * margin; - double downReach = Math.max(1D, floorCut); - for (int bz = footprint.minZ(); bz <= footprint.maxZ(); bz++) { - int footprintIndex = footprint.indexAt(footprint.minX(), bz); - for (int bx = footprint.minX(); bx <= footprint.maxX(); bx++, footprintIndex++) { - long horizontalDistanceSquared = footprint.distanceSquaredAt(footprintIndex); - if (horizontalDistanceSquared < 0L || horizontalDistanceSquared > sideReachSquared) { - continue; - } - double normalizedHorizontalDistanceSquared = sideReachSquared == 0D - ? 0D : horizontalDistanceSquared / sideReachSquared; - int sourceMinY = footprint.sourceMinYAt(footprintIndex); - int sourceMaxY = footprint.sourceMaxYAt(footprintIndex); - double upReach = eroded - ? StructureCarveEnvelope.erodedUpReach(roll, frequency, strength, bx, bz, head) - : Math.max(1D, head); - int columnUpExtension = eroded - ? (int) Math.ceil(upReach) : head; - int minY = Math.max(worldMin, sourceMinY - floorCut); - int maxY = Math.min(worldMax, sourceMaxY + columnUpExtension); - for (int by = minY; by <= maxY; by++) { - double normalizedY = StructureCarveEnvelope.normalizedVerticalDistance( - by, sourceMinY, sourceMaxY, upReach, downReach); - double distanceSquared = normalizedHorizontalDistanceSquared - + normalizedY * normalizedY; - if (distanceSquared <= 0D) { - writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN); - continue; - } - if (distanceSquared > 1D) { - continue; - } - if (!eroded) { - writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN); - continue; - } - double noise = blob.fitDouble( - 0D, 1D, bx * frequency, by * frequency, bz * frequency); - if (StructureCarveEnvelope.shouldCarveOverboreCell( - shape, distanceSquared, noise, strength)) { - writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN); - } - } - } - } - } - - private void carveOverboreBox(MantleWriter writer, int[] bounds, int margin, int head, int floorCut, - int mantleOffset, int worldMin, int worldMax) { - int minX = bounds[0] - margin; - int minY = Math.max(worldMin, bounds[1] - floorCut); - int minZ = bounds[2] - margin; - int maxX = bounds[3] + margin; - int maxY = Math.min(worldMax, bounds[4] + head); - int maxZ = bounds[5] + margin; - for (int bx = minX; bx <= maxX; bx++) { - for (int by = minY; by <= maxY; by++) { - for (int bz = minZ; bz <= maxZ; bz++) { - writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN); - } - } - } - } - - private static long overboreCandidateVolume(int[] bounds, int margin, int upExtension, - int floorCut) { - return inclusiveVolume( - bounds[0] - margin, bounds[1] - floorCut, bounds[2] - margin, - bounds[3] + margin, bounds[4] + upExtension, bounds[5] + margin); - } - - private static long inclusiveVolume(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { - long width = (long) maxX - minX + 1L; - long height = (long) maxY - minY + 1L; - long depth = (long) maxZ - minZ + 1L; - if (width <= 0L || height <= 0L || depth <= 0L - || width > Long.MAX_VALUE / height - || width * height > Long.MAX_VALUE / depth) { - return Long.MAX_VALUE; - } - return width * height * depth; - } - - private void clearIntersectingObjectTrees(MantleWriter writer, IrisStructureLocator.ResolvedPlacement resolved) { - int mantleOffset = engine.getMinHeight(); - int worldHeight = engine.getHeight(); - Map intersectingObjects = new HashMap<>(); - for (PlacedStructurePiece piece : resolved.pieces()) { - for (IrisBlockVector local : piece.getObject().getBlocks().keys()) { - PlatformBlockState structureState = piece.getObject().getBlocks().get(local); - if (!isOccupiedStructureState(structureState)) { - continue; - } - IrisBlockVector rotated = piece.getRotation().rotate(local.clone()); - int y = piece.getY() - mantleOffset + rotated.getBlockY(); - if (y >= 0 && y < worldHeight) { - collectIntersectingObjectTreeMarker( - writer, piece.getX() + rotated.getBlockX(), y, - piece.getZ() + rotated.getBlockZ(), intersectingObjects); - } - } - } - for (Map.Entry entry : intersectingObjects.entrySet()) { - clearMarkerOwnedObject(writer, entry.getKey(), entry.getValue(), worldHeight); - } - } - - static boolean isOccupiedStructureState(PlatformBlockState state) { - return !B.isAir(state); - } - - private void collectIntersectingObjectTreeMarker(MantleWriter writer, int x, int y, int z, - Map intersectingObjects) { - PlatformBlockState state = writer.getDataIfPresent(x, y, z, PlatformBlockState.class); - if (state == null || !state.isTreeBlock()) { - return; - } - String marker = writer.getDataIfPresent(x, y, z, String.class); - if (isOrdinaryObjectMarker(marker)) { - intersectingObjects.computeIfAbsent(marker, ignored -> new ObjectMarkerBounds()) - .include(x, y, z); - } - } - - private void clearMarkerOwnedObject(MantleWriter writer, String marker, - ObjectMarkerBounds intersections, int worldHeight) { - StructurePlacementMarker.Decoded decoded = StructurePlacementMarker.decode(marker); - if (decoded == null) { - return; - } - IrisObject object = engine.getData().load(IrisObject.class, decoded.objectKey(), false); - if (object == null) { - return; - } - int horizontalSpan = Math.max(1, Math.max(object.getW(), object.getD())); - int verticalSpan = Math.max(1, object.getH()); - ObjectMarkerBounds search = intersections.expand(horizontalSpan - 1, verticalSpan - 1, worldHeight); - KList positions = new KList<>(); - int minChunkX = Math.floorDiv(search.minX, 16); - int maxChunkX = Math.floorDiv(search.maxX, 16); - int minChunkZ = Math.floorDiv(search.minZ, 16); - int maxChunkZ = Math.floorDiv(search.maxZ, 16); - for (int chunkX = minChunkX; chunkX <= maxChunkX; chunkX++) { - for (int chunkZ = minChunkZ; chunkZ <= maxChunkZ; chunkZ++) { - MantleChunk chunk = writer.acquireChunk(chunkX, chunkZ); - if (chunk == null) { - continue; - } - int blockX = chunkX << 4; - int blockZ = chunkZ << 4; - chunk.iterate(String.class, (localX, y, localZ, value) -> { - int x = blockX + localX; - int z = blockZ + localZ; - if (marker.equals(value) && search.contains(x, y, z)) { - positions.add(new ObjectBlockPosition(x, y, z)); - } - }); - } - } - for (ObjectBlockPosition position : positions) { - writer.clearBlock(position.x(), position.y(), position.z()); - writer.clearData(position.x(), position.y(), position.z(), String.class); - writer.clearData(position.x(), position.y(), position.z(), TreeBlockMaterial.class); - writer.clearData(position.x(), position.y(), position.z(), TileWrapper.class); - writer.clearData(position.x(), position.y(), position.z(), MatterStructurePOI.class); - } - } - - static boolean isOrdinaryObjectMarker(String marker) { - StructurePlacementMarker.Decoded decoded = StructurePlacementMarker.decode(marker); - return decoded != null && !decoded.structureAware(); - } - - static ObjectMarkerBounds markerSearchBounds(int minX, int minY, int minZ, - int maxX, int maxY, int maxZ, - int horizontalSpan, int verticalSpan, - int worldHeight) { - ObjectMarkerBounds bounds = new ObjectMarkerBounds(); - bounds.minX = minX; - bounds.minY = minY; - bounds.minZ = minZ; - bounds.maxX = maxX; - bounds.maxY = maxY; - bounds.maxZ = maxZ; - return bounds.expand( - Math.max(0, horizontalSpan - 1), Math.max(0, verticalSpan - 1), worldHeight); - } - - private int[] computePieceBounds(KList pieces) { - if (pieces == null || pieces.isEmpty()) { - return null; - } - int minX = Integer.MAX_VALUE; - int minY = Integer.MAX_VALUE; - int minZ = Integer.MAX_VALUE; - int maxX = Integer.MIN_VALUE; - int maxY = Integer.MIN_VALUE; - int maxZ = Integer.MIN_VALUE; - for (PlacedStructurePiece p : pieces) { - minX = Math.min(minX, p.getMinX()); - minY = Math.min(minY, p.getMinY()); - minZ = Math.min(minZ, p.getMinZ()); - maxX = Math.max(maxX, p.getMaxX()); - maxY = Math.max(maxY, p.getMaxY()); - maxZ = Math.max(maxZ, p.getMaxZ()); - } - return new int[]{minX, minY, minZ, maxX, maxY, maxZ}; - } - - private int placeObject(MantleWriter writer, IrisStructure structure, PlacedStructurePiece p, - ObjectPlaceMode mode, int y, RNG rng, Long2IntOpenHashMap foundationColumns, - boolean supportNonOccluding) { - IrisObject object = p.getObject(); - String objectKey = object.getLoadKey(); - IrisObjectPlacement config = structure.createLootPlacement(objectKey); - config.setMode(mode); - config.setRotation(p.getRotation()); - if (!structure.getEdit().isEmpty()) { - config.setEdit(structure.getEdit()); - } - if (!mode.placeMode().has(PlaceTrait.FREE_HEIGHT)) { - config.setForcePlace(true); - } - int placeY = (y == -1) ? -1 : y - engine.getMinHeight(); - String marker = structurePlacementMarker(structure, p, objectKey); - return object.place(p.getX(), placeY, p.getZ(), writer, config, rng, (position, state) -> { - StructureFoundationPlanner.recordBaseCell( - foundationColumns, position.getX(), position.getY(), position.getZ(), state, - supportNonOccluding); - if (marker != null && shouldWriteStructureMarker(state)) { - writer.setData(position.getX(), position.getY(), position.getZ(), marker); - } - }, null, engine.getData()); - } - - static boolean shouldWriteStructureMarker(PlatformBlockState state) { - return state != null && state.isStorageChest(); - } - - static int structurePlacementId(String structureKey, String objectKey, int x, int y, int z) { - int hash = 17; - hash = 31 * hash + structureKey.hashCode(); - hash = 31 * hash + objectKey.hashCode(); - hash = 31 * hash + x; - hash = 31 * hash + y; - hash = 31 * hash + z; - return hash & Integer.MAX_VALUE; - } - - private static String structurePlacementMarker(IrisStructure structure, PlacedStructurePiece piece, String objectKey) { - String structureKey = structure.getLoadKey(); - if (structureKey == null || structureKey.isBlank() || objectKey == null || objectKey.isBlank()) { - return null; - } - int placementId = structurePlacementId(structureKey, objectKey, piece.getX(), piece.getY(), piece.getZ()); - return StructurePlacementMarker.encodeStructure(objectKey, placementId, structureKey); - } - - /** How far, in blocks along X and Z, placements may write beyond their chunk. */ - public int reach() { - IrisDimension dimension = engine.getDimension(); - int maxBlocks = 0; - - for (IrisRegion region : dimension.getAllRegions(engine)) { - maxBlocks = Math.max(maxBlocks, maxBlocksFrom(StructurePlacementScope.placementsOf(region))); - } - for (IrisBiome biome : dimension.getReachableBiomes(engine)) { - maxBlocks = Math.max(maxBlocks, maxBlocksFrom(StructurePlacementScope.placementsOf(biome))); - } - maxBlocks = Math.max(maxBlocks, maxBlocksFrom(StructurePlacementScope.placementsOf(dimension))); - - return maxBlocks; - } - - private int maxBlocksFrom(List placements) { - int max = 0; - for (StructurePlacement placement : placements) { - if (!placement.hasIrisStructures()) { - continue; - } - StructureTerrain terrain = placement.resolvedTerrain(); - int carvePadding = terrain.resolvedMode() == StructureTerrainMode.FORCE_CARVE - || terrain.resolvedMode() == StructureTerrainMode.BORE - ? Math.max(0, terrain.horizontalPadding()) : 0; - for (String key : placement.structures()) { - IrisStructure structure = StructureResources.structure(engine.getData(), key); - if (structure != null) { - max = Math.max(max, Math.max(1, structure.getMaxSizeChunks()) * 16 + carvePadding); - } - } - } - return max; - } - - static final class ObjectMarkerBounds { - private int minX = Integer.MAX_VALUE; - private int minY = Integer.MAX_VALUE; - private int minZ = Integer.MAX_VALUE; - private int maxX = Integer.MIN_VALUE; - private int maxY = Integer.MIN_VALUE; - private int maxZ = Integer.MIN_VALUE; - - void include(int x, int y, int z) { - minX = Math.min(minX, x); - minY = Math.min(minY, y); - minZ = Math.min(minZ, z); - maxX = Math.max(maxX, x); - maxY = Math.max(maxY, y); - maxZ = Math.max(maxZ, z); - } - - ObjectMarkerBounds expand(int horizontal, int vertical, int worldHeight) { - ObjectMarkerBounds expanded = new ObjectMarkerBounds(); - expanded.minX = minX - horizontal; - expanded.minY = Math.max(0, minY - vertical); - expanded.minZ = minZ - horizontal; - expanded.maxX = maxX + horizontal; - expanded.maxY = Math.min(worldHeight - 1, maxY + vertical); - expanded.maxZ = maxZ + horizontal; - return expanded; - } - - boolean contains(int x, int y, int z) { - return x >= minX && x <= maxX - && y >= minY && y <= maxY - && z >= minZ && z <= maxZ; - } - - int minX() { - return minX; - } - - int minY() { - return minY; - } - - int minZ() { - return minZ; - } - - int maxX() { - return maxX; - } - - int maxY() { - return maxY; - } - - int maxZ() { - return maxZ; - } - } - - private record ObjectBlockPosition(int x, int y, int z) { - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListFunction.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListFunction.java deleted file mode 100644 index d1157b77a..000000000 --- a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListFunction.java +++ /dev/null @@ -1,18 +0,0 @@ -package art.arcane.iris.engine.object.annotations; - -import art.arcane.iris.engine.framework.ListFunction; -import art.arcane.volmlib.util.collection.KList; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.ElementType.PARAMETER; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -@Retention(RUNTIME) -@Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListFunction { - Class>> value(); -} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/functions/ComponentFlagFunction.java b/src/main/java/art/arcane/iris/engine/object/annotations/functions/ComponentFlagFunction.java deleted file mode 100644 index f4d2abf51..000000000 --- a/src/main/java/art/arcane/iris/engine/object/annotations/functions/ComponentFlagFunction.java +++ /dev/null @@ -1,30 +0,0 @@ -package art.arcane.iris.engine.object.annotations.functions; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.MantleStageFlags; -import art.arcane.iris.engine.framework.ListFunction; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.mantle.flag.MantleFlag; - -/** - * What studio offers for a dimension's {@code disabledComponents}: the flags of Iris's own mantle stages, such as - * {@code CARVED} for caves, then the ids of the pack's mantle stages. - */ -public class ComponentFlagFunction implements ListFunction> { - @Override - public String key() { - return "component-flag"; - } - - @Override - public String fancyName() { - return "Component Flag"; - } - - @Override - public KList apply(IrisData data) { - KList names = MantleStageFlags.builtIn().stream().map(MantleFlag::toString).collect(KList.collector()); - names.addAll(MantleStageFlags.packStageIds(data.getModules().pack().mantle().stages())); - return names; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/functions/LootTableKeyFunction.java b/src/main/java/art/arcane/iris/engine/object/annotations/functions/LootTableKeyFunction.java deleted file mode 100644 index 37107e219..000000000 --- a/src/main/java/art/arcane/iris/engine/object/annotations/functions/LootTableKeyFunction.java +++ /dev/null @@ -1,23 +0,0 @@ -package art.arcane.iris.engine.object.annotations.functions; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.ListFunction; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.volmlib.util.collection.KList; - -public class LootTableKeyFunction implements ListFunction> { - @Override - public String key() { - return "loot-table-key"; - } - - @Override - public String fancyName() { - return "LootTable Key"; - } - - @Override - public KList apply(IrisData data) { - return new KList<>(IrisPlatforms.get().registries().lootTableKeys()); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompat.java b/src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompat.java deleted file mode 100644 index 62ee6fec4..000000000 --- a/src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompat.java +++ /dev/null @@ -1,381 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.compatibility; - -import art.arcane.iris.platform.bukkit.BukkitBlockResolution; - -import art.arcane.iris.spi.IrisLogging; -import com.google.gson.Gson; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.io.IO; -import art.arcane.volmlib.util.json.JSONObject; -import art.arcane.iris.util.common.scheduling.J; -import lombok.Data; -import org.bukkit.Material; -import org.bukkit.block.data.BlockData; - -import java.io.File; -import java.io.IOException; - -@Data -public class IrisCompat { - private KList blockFilters; - private KList itemFilters; - - public IrisCompat() { - blockFilters = getDefaultBlockCompatabilityFilters(); - itemFilters = getDefaultItemCompatabilityFilters(); - } - - public static IrisCompat configured(File f) { - IrisCompat def = new IrisCompat(); - String defa = new JSONObject(new Gson().toJson(def)).toString(4); - J.attemptAsync(() -> IO.writeAll(new File(f.getParentFile(), "compat.default.json"), defa)); - - - if (!f.exists()) { - J.a(() -> { - try { - IO.writeAll(f, defa); - } catch (IOException e) { - IrisLogging.error("Failed to writeNodeData to compat file"); - IrisLogging.reportError(e); - } - }); - } else { - // If the file doesn't exist, no additional mappings are present outside default - // so we shouldn't try getting them - try { - IrisCompat rea = new Gson().fromJson(IO.readAll(f), IrisCompat.class); - - for (IrisCompatabilityBlockFilter i : rea.getBlockFilters()) { - def.getBlockFilters().add(i); - } - - for (IrisCompatabilityItemFilter i : rea.getItemFilters()) { - def.getItemFilters().add(i); - } - } catch (Throwable e) { - IrisLogging.reportError(e); - } - } - - return def; - } - - private static KList getDefaultItemCompatabilityFilters() { - KList filters = new KList<>(); - - // Below 1.16 - filters.add(new IrisCompatabilityItemFilter("NETHERITE_HELMET", "DIAMOND_HELMET")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_CHESTPLATE", "DIAMOND_CHESTPLATE")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_BOOTS", "DIAMOND_BOOTS")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_LEGGINGS", "DIAMOND_LEGGINGS")); - filters.add(new IrisCompatabilityItemFilter("MUSIC_DISC_PIGSTEP", "MUSIC_DISC_FAR")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_SWORD", "DIAMOND_SWORD")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_AXE", "DIAMOND_AXE")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_PICKAXE", "DIAMOND_PICKAXE")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_HOE", "DIAMOND_HOE")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_SHOVEL", "DIAMOND_SHOVEL")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_INGOT", "DIAMOND")); - filters.add(new IrisCompatabilityItemFilter("PIGLIN_BANNER_PATTERN", "PORKCHOP")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_SCRAP", "GOLD_INGOT")); - filters.add(new IrisCompatabilityItemFilter("WARPED_FUNGUS_ON_A_STICK", "CARROT_ON_A_STICK")); - - // Below 1.15 - filters.add(new IrisCompatabilityItemFilter("HONEY_BOTTLE", "GLASS_BOTTLE")); - filters.add(new IrisCompatabilityItemFilter("HONEYCOMB", "GLASS")); - - // Below 1.14 - filters.add(new IrisCompatabilityItemFilter("SWEET_BERRIES", "APPLE")); - filters.add(new IrisCompatabilityItemFilter("SUSPICIOUS_STEW", "MUSHROOM_STEW")); - filters.add(new IrisCompatabilityItemFilter("BLACK_DYE", "INK_SAC")); - filters.add(new IrisCompatabilityItemFilter("WHITE_DYE", "BONE_MEAL")); - filters.add(new IrisCompatabilityItemFilter("BROWN_DYE", "COCOA_BEANS")); - filters.add(new IrisCompatabilityItemFilter("BLUE_DYE", "LAPIS_LAZULI")); - filters.add(new IrisCompatabilityItemFilter("CROSSBOW", "BOW")); - filters.add(new IrisCompatabilityItemFilter("FLOWER_BANNER_PATTERN", "CORNFLOWER")); - filters.add(new IrisCompatabilityItemFilter("SKULL_BANNER_PATTERN", "BONE")); - filters.add(new IrisCompatabilityItemFilter("GLOBE_BANNER_PATTERN", "WHEAT_SEEDS")); - filters.add(new IrisCompatabilityItemFilter("MOJANG_BANNER_PATTERN", "DIRT")); - filters.add(new IrisCompatabilityItemFilter("CREEPER_BANNER_PATTERN", "CREEPER_HEAD")); - - return filters; - } - - private static KList getDefaultBlockCompatabilityFilters() { - KList filters = new KList<>(); - - filters.add(new IrisCompatabilityBlockFilter("CHAIN", "IRON_CHAIN")); - filters.add(new IrisCompatabilityBlockFilter("GRASS", "SHORT_GRASS")); - filters.add(new IrisCompatabilityBlockFilter("SHORT_GRASS", "GRASS")); - - // Below 1.16 - filters.add(new IrisCompatabilityBlockFilter("WEEPING_VINES", "NETHER_FENCE")); - filters.add(new IrisCompatabilityBlockFilter("WEEPING_VINES_PLANT", "NETHER_FENCE")); - filters.add(new IrisCompatabilityBlockFilter("WARPED_WART_BLOCK", "NETHER_WART_BLOCK")); - filters.add(new IrisCompatabilityBlockFilter("TWISTING_VINES", "BAMBOO")); - filters.add(new IrisCompatabilityBlockFilter("TWISTING_VINES_PLANT", "BAMBOO")); - filters.add(new IrisCompatabilityBlockFilter("TARGET", "COBBLESTONE")); - filters.add(new IrisCompatabilityBlockFilter("SOUL_SOIL", "SOULSAND")); - filters.add(new IrisCompatabilityBlockFilter("SOUL_TORCH", "TORCH")); - filters.add(new IrisCompatabilityBlockFilter("SOUL_LANTERN", "LANTERN")); - filters.add(new IrisCompatabilityBlockFilter("SOUL_FIRE", "FIRE")); - filters.add(new IrisCompatabilityBlockFilter("SOUL_CAMPFIRE", "CAMPFIRE")); - filters.add(new IrisCompatabilityBlockFilter("SHROOMLIGHT", "GLOWSTONE")); - filters.add(new IrisCompatabilityBlockFilter("RESPAWN_ANCHOR", "OBSIDIAN")); - filters.add(new IrisCompatabilityBlockFilter("NETHER_SPROUTS", "RED_MUSHROOM")); - filters.add(new IrisCompatabilityBlockFilter("NETHER_GOLD_ORE", "GOLD_ORE")); - filters.add(new IrisCompatabilityBlockFilter("LODESTONE", "STONE")); - filters.add(new IrisCompatabilityBlockFilter("STRIPPED_WARPED_HYPHAE", "BROWN_MUSHROOM_BLOCK")); - filters.add(new IrisCompatabilityBlockFilter("STRIPPED_CRIMSON_HYPHAE", "RED_MUSHROOM_BLOCK")); - filters.add(new IrisCompatabilityBlockFilter("WARPED_HYPHAE", "MUSHROOM_STEM")); - filters.add(new IrisCompatabilityBlockFilter("CRIMSON_HYPHAE", "RED_MUSHROOM_BLOCK")); - filters.add(new IrisCompatabilityBlockFilter("GILDED_BLACKSTONE", "COBBLESTONE")); - filters.add(new IrisCompatabilityBlockFilter("CRYING_OBSIDIAN", "OBSIDIAN")); - filters.add(new IrisCompatabilityBlockFilter("STRIPPED_WARPED_STEM", "MUSHROOM_STEM")); - filters.add(new IrisCompatabilityBlockFilter("STRIPPED_CRIMSON_STEM", "MUSHROOM_STEM")); - filters.add(new IrisCompatabilityBlockFilter("WARPED_STEM", "MUSHROOM_STEM")); - filters.add(new IrisCompatabilityBlockFilter("CRIMSON_STEM", "MUSHROOM_STEM")); - filters.add(new IrisCompatabilityBlockFilter("CRIMSON_ROOTS", "RED_MUSHROOM")); - filters.add(new IrisCompatabilityBlockFilter("WARPED_ROOTS", "BROWN_MUSHROOM")); - filters.add(new IrisCompatabilityBlockFilter("CRIMSON_PLANKS", "OAK_PLANKS")); - filters.add(new IrisCompatabilityBlockFilter("WARPED_PLANKS", "OAK_PLANKS")); - filters.add(new IrisCompatabilityBlockFilter("WARPED_NYLIUM", "MYCELIUM")); - filters.add(new IrisCompatabilityBlockFilter("CRIMSON_NYLIUM", "MYCELIUM")); - filters.add(new IrisCompatabilityBlockFilter("WARPED_FUNGUS", "BROWN_MUSHROOM")); - filters.add(new IrisCompatabilityBlockFilter("CRIMSON_FUNGUS", "RED_MUSHROOM")); - filters.add(new IrisCompatabilityBlockFilter("CRACKED_NETHER_BRICKS", "NETHER_BRICKS")); - filters.add(new IrisCompatabilityBlockFilter("CHISELED_NETHER_BRICKS", "NETHER_BRICKS")); - filters.add(new IrisCompatabilityBlockFilter("NETHER_FENCE", "LEGACY_NETHER_FENCE")); - filters.add(new IrisCompatabilityBlockFilter("IRON_CHAIN", "IRON_BARS")); - filters.add(new IrisCompatabilityBlockFilter("NETHERITE_BLOCK", "QUARTZ_BLOCK")); - filters.add(new IrisCompatabilityBlockFilter("BLACKSTONE", "COBBLESTONE")); - filters.add(new IrisCompatabilityBlockFilter("BASALT", "STONE")); - filters.add(new IrisCompatabilityBlockFilter("ANCIENT_DEBRIS", "NETHERRACK")); - filters.add(new IrisCompatabilityBlockFilter("NETHERRACK", "LEGACY_NETHERRACK")); - - // Below 1.15 - filters.add(new IrisCompatabilityBlockFilter("HONEY_BLOCK", "OAK_LEAVES")); - filters.add(new IrisCompatabilityBlockFilter("BEEHIVE", "OAK_LEAVES")); - filters.add(new IrisCompatabilityBlockFilter("BEE_NEST", "OAK_LEAVES")); - - // Below 1.14 - filters.add(new IrisCompatabilityBlockFilter("GRANITE_WALL", "COBBLESTONE_WALL")); - filters.add(new IrisCompatabilityBlockFilter("BLUE_ICE", "PACKED_ICE")); - filters.add(new IrisCompatabilityBlockFilter("DIORITE_WALL", "COBBLESTONE_WALL")); - filters.add(new IrisCompatabilityBlockFilter("ANDESITE_WALL", "COBBLESTONE_WALL")); - filters.add(new IrisCompatabilityBlockFilter("SWEET_BERRY_BUSH", "GRASS")); - filters.add(new IrisCompatabilityBlockFilter("STONECUTTER", "CRAFTING_TABLE")); - filters.add(new IrisCompatabilityBlockFilter("SANDSTONE_STAIRS", "LEGACY_SANDSTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("SMOOTH_SANDSTONE_STAIRS", "LEGACY_SANDSTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("MOSSY_COBBLESTONE_STAIRS", "COBBLESTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("MOSSY_STONE_BRICK_STAIRS", "STONE_BRICK_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("POLISHED_GRANITE_STAIRS", "COBBLESTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("GRANITE_STAIRS", "COBBLESTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("POLISHED_DIORITE_STAIRS", "COBBLESTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("DIORITE_STAIRS", "COBBLESTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("POLISHED_ANDESITE_STAIRS", "COBBLESTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("ANDESITE_STAIRS", "COBBLESTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("STONE_STAIRS", "COBBLESTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("END_STONE_BRICK_STAIRS", "LEGACY_SANDSTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("NETHER_BRICK_STAIRS", "LEGACY_NETHER_BRICK_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("RED_NETHER_BRICK_STAIRS", "NETHER_BRICK_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("SMOOTH_QUARTZ_STAIRS", "LEGACY_QUARTZ_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("QUARTZ_STAIRS", "LEGACY_QUARTZ_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("RED_SANDSTONE_STAIRS", "LEGACY_RED_SANDSTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("SMOOTH_RED_SANDSTONE_STAIRS", "LEGACY_RED_SANDSTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("STONE_SLAB", "SMOOTH_STONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("SMOKER", "FURNACE")); - filters.add(new IrisCompatabilityBlockFilter("SMITHING_TABLE", "CRAFTING_TABLE")); - filters.add(new IrisCompatabilityBlockFilter("END_STONE_BRICK_SLAB", "SANDSTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("RED_NETHER_BRICK_SLAB", "NETHER_BRICK_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("SMOOTH_QUARTZ_SLAB", "QUARTZ_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("CUT_SANDSTONE_SLAB", "SANDSTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("CUT_RED_SANDSTONE_SLAB", "RED_SANDSTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("SMOOTH_RED_SANDSTONE_SLAB", "RED_SANDSTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("SMOOTH_SANDSTONE_SLAB", "SANDSTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("MOSSY_COBBLESTONE_SLAB", "COBBLESTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("MOSSY_STONE_BRICK_SLAB", "STONE_BRICK_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("STONE_SLAB", "SMOOTH_STONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("ANDESITE_SLAB", "COBBLESTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("ANDESITE_SLAB", "COBBLESTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("DIORITE_SLAB", "COBBLESTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("GRANITE_SLAB", "COBBLESTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("POLISHED_ANDESITE_SLAB", "SMOOTH_STONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("POLISHED_DIORITE_SLAB", "SMOOTH_STONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("POLISHED_GRANITE_SLAB", "SMOOTH_STONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("WARPED_WALL_SIGN", "LEGACY_WALL_SIGN")); - filters.add(new IrisCompatabilityBlockFilter("WARPED_SIGN", "LEGACY_SIGN_POST")); - filters.add(new IrisCompatabilityBlockFilter("SPRUCE_WALL_SIGN", "LEGACY_WALL_SIGN")); - filters.add(new IrisCompatabilityBlockFilter("SPRUCE_SIGN", "LEGACY_SIGN_POST")); - filters.add(new IrisCompatabilityBlockFilter("OAK_WALL_SIGN", "LEGACY_WALL_SIGN")); - filters.add(new IrisCompatabilityBlockFilter("OAK_SIGN", "LEGACY_SIGN_POST")); - filters.add(new IrisCompatabilityBlockFilter("JUNGLE_WALL_SIGN", "LEGACY_WALL_SIGN")); - filters.add(new IrisCompatabilityBlockFilter("JUNGLE_SIGN", "LEGACY_SIGN_POST")); - filters.add(new IrisCompatabilityBlockFilter("DARK_OAK_WALL_SIGN", "LEGACY_WALL_SIGN")); - filters.add(new IrisCompatabilityBlockFilter("DARK_OAK_SIGN", "LEGACY_SIGN_POST")); - filters.add(new IrisCompatabilityBlockFilter("CRIMSON_WALL_SIGN", "LEGACY_WALL_SIGN")); - filters.add(new IrisCompatabilityBlockFilter("CRIMSON_SIGN", "LEGACY_SIGN_POST")); - filters.add(new IrisCompatabilityBlockFilter("BIRCH_WALL_SIGN", "LEGACY_WALL_SIGN")); - filters.add(new IrisCompatabilityBlockFilter("BIRCH_SIGN", "LEGACY_SIGN_POST")); - filters.add(new IrisCompatabilityBlockFilter("ACACIA_WALL_SIGN", "LEGACY_WALL_SIGN")); - filters.add(new IrisCompatabilityBlockFilter("ACACIA_SIGN", "LEGACY_SIGN_POST")); - filters.add(new IrisCompatabilityBlockFilter("SCAFFOLDING", "BIRCH_FENCE")); - //filters.add(new IrisCompatabilityBlockFilter("LOOM", "LOOM")); - filters.add(new IrisCompatabilityBlockFilter("LECTERN", "BOOKSHELF")); - filters.add(new IrisCompatabilityBlockFilter("LANTERN", "REDSTONE_LAMP")); - filters.add(new IrisCompatabilityBlockFilter("JIGSAW", "AIR")); - filters.add(new IrisCompatabilityBlockFilter("GRINDSTONE", "COBBLESTONE")); - filters.add(new IrisCompatabilityBlockFilter("FLETCHING_TABLE", "CRAFTING_TABLE")); - filters.add(new IrisCompatabilityBlockFilter("COMPOSTER", "CHEST")); - filters.add(new IrisCompatabilityBlockFilter("CARTOGRAPHY_TABLE", "CRAFTING_TABLE")); - filters.add(new IrisCompatabilityBlockFilter("CAMPFIRE", "DARK_OAK_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("BLAST_FURNACE", "FURNACE")); - filters.add(new IrisCompatabilityBlockFilter("BELL", "REDSTONE_LAMP")); - filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=south]", "minecraft:hay_bale[axis=z]", true)); - filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=north]", "minecraft:hay_bale[axis=z]", true)); - filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=east]", "minecraft:hay_bale[axis=x]", true)); - filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=west]", "minecraft:hay_bale[axis=x]", true)); - filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=up]", "minecraft:hay_bale[axis=y]", true)); - filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=down]", "minecraft:hay_bale[axis=y]", true)); - filters.add(new IrisCompatabilityBlockFilter("BAMBOO", "BIRCH_FENCE")); - filters.add(new IrisCompatabilityBlockFilter("BAMBOO_SAPLING", "BIRCH_SAPLING")); - filters.add(new IrisCompatabilityBlockFilter("POTTED_BAMBOO", "POTTED_BIRCH_SAPLING")); - - return filters; - } - - public BlockData getBlock(String n) { - String buf = n; - int err = 16; - - BlockData tx = BukkitBlockResolution.getOrNull(buf, false); - - if (tx != null) { - return tx; - } - - searching: - while (true) { - if (err-- <= 0) { - IrisLogging.warnOnce("compat-block:" + n, "Can't find block data for " + n + "; using STONE."); - return BukkitBlockResolution.getNoCompat("STONE"); - } - String m = buf; - if (m.contains("[")) { - m = m.split("\\Q[\\E")[0]; - } - if (m.contains(":")) { - m = m.split("\\Q:\\E", 2)[1]; - } - - for (IrisCompatabilityBlockFilter i : blockFilters) { - if (i.getWhen().equalsIgnoreCase(i.isExact() ? buf : m)) { - BlockData b = i.getReplace(); - - if (b != null) { - return b; - } - - buf = i.getSupplement(); - continue searching; - } - } - - IrisLogging.warnOnce("compat-block:" + n, "Can't find block data for " + n + "; using STONE."); - return BukkitBlockResolution.getNoCompat("STONE"); - } - } - - public Material getItem(String n) { - String buf = n; - int err = 16; - Material txf = BukkitBlockResolution.getMaterialOrNull(buf); - - if (txf != null) { - return txf; - } - - int nomore = 64; - - searching: - while (true) { - if (nomore < 0) { - return BukkitBlockResolution.getMaterial("STONE"); - } - - nomore--; - if (err-- <= 0) { - break; - } - - for (IrisCompatabilityItemFilter i : itemFilters) { - if (i.getWhen().equalsIgnoreCase(buf)) { - Material b = i.getReplace(); - - if (b != null) { - return b; - } - - buf = i.getSupplement(); - continue searching; - } - } - - break; - } - - buf = n; - BlockData tx = BukkitBlockResolution.getOrNull(buf, false); - - if (tx != null) { - return tx.getMaterial(); - } - nomore = 64; - - searching: - while (true) { - if (nomore < 0) { - return BukkitBlockResolution.getMaterial("STONE"); - } - - nomore--; - - if (err-- <= 0) { - return BukkitBlockResolution.getMaterial("STONE"); - } - - for (IrisCompatabilityBlockFilter i : blockFilters) { - if (i.getWhen().equalsIgnoreCase(buf)) { - BlockData b = i.getReplace(); - - if (b != null) { - return b.getMaterial(); - } - - buf = i.getSupplement(); - continue searching; - } - } - - return BukkitBlockResolution.getMaterial("STONE"); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompatabilityBlockFilter.java b/src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompatabilityBlockFilter.java deleted file mode 100644 index ee3dc6962..000000000 --- a/src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompatabilityBlockFilter.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.compatibility; - -import art.arcane.iris.platform.bukkit.BukkitBlockResolution; - -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.spi.IrisLogging; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.block.data.BlockData; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Find and replace object materials for compatability") -@Data -public class IrisCompatabilityBlockFilter { - private final transient AtomicCache findData = new AtomicCache<>(true); - private final transient AtomicCache replaceData = new AtomicCache<>(true); - @Required - @Desc("When iris sees this block, and it's not reconized") - private String when = ""; - @Required - @Desc("Replace it with this block. Dont worry if this block is also not reconized, iris repeat this compat check.") - private String supplement = ""; - @Desc("If exact is true, it compares block data for example minecraft:some_log[axis=x]") - private boolean exact = false; - - public IrisCompatabilityBlockFilter(String when, String supplement) { - this(when, supplement, false); - } - - public BlockData getFind() { - return findData.aquire(() -> BukkitBlockResolution.get(when)); - } - - public BlockData getReplace() { - return replaceData.aquire(() -> - { - BlockData b = BukkitBlockResolution.getOrNull(supplement, false); - - if (b == null) { - return null; - } - - IrisLogging.warn("Compat: Using '%s' in place of '%s' since this server doesnt support '%s'", supplement, when, when); - - return b; - }); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompatabilityItemFilter.java b/src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompatabilityItemFilter.java deleted file mode 100644 index 6886115eb..000000000 --- a/src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompatabilityItemFilter.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.compatibility; - -import art.arcane.iris.platform.bukkit.BukkitBlockResolution; - -import art.arcane.iris.spi.IrisLogging; -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.Required; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.Material; - -@Accessors(chain = true) -@NoArgsConstructor -@Desc("Find and replace object items for compatability") -@Data -public class IrisCompatabilityItemFilter { - private final transient AtomicCache findData = new AtomicCache<>(true); - private final transient AtomicCache replaceData = new AtomicCache<>(true); - @Required - @Desc("When iris sees this block, and it's not reconized") - private String when = ""; - @Required - @Desc("Replace it with this block. Dont worry if this block is also not reconized, iris repeat this compat check.") - private String supplement = ""; - - public IrisCompatabilityItemFilter(String when, String supplement) { - this.when = when; - this.supplement = supplement; - } - - public Material getFind() { - return findData.aquire(() -> BukkitBlockResolution.getMaterial(when)); - } - - public Material getReplace() { - return replaceData.aquire(() -> - { - Material b = BukkitBlockResolution.getMaterialOrNull(supplement); - - if (b == null) { - return null; - } - - IrisLogging.debug("Compat: Using " + supplement + " in place of " + when + " since this server doesnt support '" + supplement + "'"); - - return b; - }); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImage.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImage.java deleted file mode 100644 index 906f8d87b..000000000 --- a/src/main/java/art/arcane/iris/engine/object/image/IrisImage.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.image; - -import art.arcane.iris.core.loader.IrisRegistrant; - -import java.awt.image.ColorModel; -import java.awt.image.BufferedImage; -import java.awt.image.IndexColorModel; -import java.awt.image.Raster; -import java.util.Objects; - -public final class IrisImage extends IrisRegistrant { - private final BufferedImage image; - private final Raster raster; - private final ColorModel colorModel; - private final String format; - - public IrisImage() { - this(new BufferedImage(4, 4, BufferedImage.TYPE_INT_RGB), "png"); - } - - public IrisImage(BufferedImage image) { - this(image, "png"); - } - - public IrisImage(BufferedImage image, String format) { - this.image = Objects.requireNonNull(image, "IrisImage requires a decoded image (the source file was unreadable or not an image)"); - this.raster = image.getRaster(); - this.colorModel = image.getColorModel(); - this.format = Objects.requireNonNull(format, "Image format").toLowerCase(); - } - - public int getWidth() { - return image.getWidth(); - } - - public int getHeight() { - return image.getHeight(); - } - - public String getFormat() { - return format; - } - - public IrisImageColorMode getColorMode() { - if (colorModel instanceof IndexColorModel) { - return IrisImageColorMode.INDEXED; - } - int colorComponents = colorModel.getNumColorComponents(); - if (colorComponents == 1) { - return colorModel.hasAlpha() ? IrisImageColorMode.UNSUPPORTED : IrisImageColorMode.GRAYSCALE; - } - if (colorComponents == 3) { - return colorModel.hasAlpha() ? IrisImageColorMode.RGBA : IrisImageColorMode.RGB; - } - return IrisImageColorMode.UNSUPPORTED; - } - - public int getColorComponentCount() { - return colorModel.getNumColorComponents(); - } - - public int getChannelCount() { - return raster.getNumBands(); - } - - public int getBitDepth() { - int[] sampleSizes = raster.getSampleModel().getSampleSize(); - int maximum = 0; - int colorBands = Math.min(getColorComponentCount(), sampleSizes.length); - for (int index = 0; index < colorBands; index++) { - maximum = Math.max(maximum, sampleSizes[index]); - } - return maximum; - } - - public boolean hasAlpha() { - return colorModel.hasAlpha(); - } - - public double getBandNormalized(int x, int z, int band) { - requireCoordinate(x, z); - if (band < 0 || band >= raster.getNumBands()) { - throw new IllegalArgumentException("Image band " + band + " is outside 0.." + (raster.getNumBands() - 1)); - } - int bits = raster.getSampleModel().getSampleSize(band); - long maximum = (1L << bits) - 1L; - return raster.getSample(x, z, band) / (double) maximum; - } - - public int getBandSample(int x, int z, int band) { - requireCoordinate(x, z); - if (band < 0 || band >= raster.getNumBands()) { - throw new IllegalArgumentException("Image band " + band + " is outside 0.." + (raster.getNumBands() - 1)); - } - return raster.getSample(x, z, band); - } - - public double getAlphaNormalized(int x, int z) { - requireCoordinate(x, z); - if (!hasAlpha()) { - return 1D; - } - int alphaBand = raster.getNumBands() - 1; - return getBandNormalized(x, z, alphaBand); - } - - public int getRawRgb8(int x, int z) { - requireCoordinate(x, z); - IrisImageColorMode mode = getColorMode(); - if (mode != IrisImageColorMode.RGB && mode != IrisImageColorMode.RGBA) { - throw new IllegalStateException("Raw RGB sampling requires an RGB or RGBA image, not " + mode); - } - int red = scaleTo8Bit(x, z, 0); - int green = scaleTo8Bit(x, z, 1); - int blue = scaleTo8Bit(x, z, 2); - return red << 16 | green << 8 | blue; - } - - public int getPreviewArgb(int x, int z) { - requireCoordinate(x, z); - return image.getRGB(x, z); - } - - private int scaleTo8Bit(int x, int z, int band) { - int bits = raster.getSampleModel().getSampleSize(band); - int sample = raster.getSample(x, z, band); - if (bits == 8) { - return sample; - } - long maximum = (1L << bits) - 1L; - return (int) Math.round(sample * 255D / maximum); - } - - private void requireCoordinate(int x, int z) { - if (x < 0 || z < 0 || x >= getWidth() || z >= getHeight()) { - throw new IndexOutOfBoundsException("Image coordinate " + x + "," + z + " is outside " + getWidth() + "x" + getHeight()); - } - } - - @Override - public String getFolderName() { - return "images"; - } - - @Override - public String getTypeName() { - return "Image"; - } - -} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMap.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMap.java deleted file mode 100644 index e28062058..000000000 --- a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMap.java +++ /dev/null @@ -1,120 +0,0 @@ -package art.arcane.iris.engine.object.image; - -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.volmlib.util.collection.KMap; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@NoArgsConstructor -@Desc("A reusable typed image-map definition") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisImageMap extends IrisRegistrant { - public static final double MINIMUM_SCALE = 0.000001D; - public static final double MAXIMUM_COLOR_TOLERANCE = 441.672956D; - - @RegistryListResource(IrisImage.class) - @Desc("PNG source under images/, without the file extension") - private String source = ""; - - @Desc("How source pixels are decoded") - private IrisImageMapType type = IrisImageMapType.GRAYSCALE_HEIGHT; - - @MinNumber(MINIMUM_SCALE) - @Desc("Minecraft blocks represented by one source pixel") - private double blocksPerPixel = 1D; - - @Desc("Minecraft X/Z coordinate that maps to sourceOrigin") - private IrisImageMapOrigin origin = new IrisImageMapOrigin(); - - @Desc("Source pixel X/Y coordinate placed at origin") - private IrisImageMapOrigin sourceOrigin = new IrisImageMapOrigin(); - - @Desc("Clockwise quarter-turn rotation around sourceOrigin") - private IrisImageMapRotation rotation = IrisImageMapRotation.DEG_0; - - @Desc("Mirror image X around sourceOrigin before rotation") - private boolean mirrorX = false; - - @Desc("Mirror image Y around sourceOrigin before rotation") - private boolean mirrorZ = false; - - @Desc("Numeric sampling filter; exact color and binary maps require NEAREST") - private IrisImageMapSampling sampling = IrisImageMapSampling.NEAREST; - - @Desc("Behavior outside the source rectangle") - private IrisImageMapOutOfBounds outOfBounds = IrisImageMapOutOfBounds.FALLBACK; - - @MinNumber(0) - @MaxNumber(1) - @Desc("Normalized scalar used by FALLBACK coordinates") - private double fallbackValue = 0D; - - @Desc("Legend target used by FALLBACK or unknown color-map pixels") - private String fallbackTarget = ""; - - @Desc("How alpha affects decoded data") - private IrisImageMapAlpha alpha = IrisImageMapAlpha.IGNORE; - - @Desc("Minimum absolute world Y for height maps") - private double minimumHeight = -64D; - - @Desc("Maximum absolute world Y for height maps") - private double maximumHeight = 320D; - - @Desc("Vertical block offset applied after height decoding") - private double verticalOffset = 0D; - - @Desc("Clamp decoded height to minimumHeight and maximumHeight after offset") - private boolean clamp = true; - - @Desc("Invert decoded scalar values before curve evaluation") - private boolean inverted = false; - - @MinNumber(MINIMUM_SCALE) - @Desc("Power curve applied after optional inversion; 1 is linear") - private double curveExponent = 1D; - - @MinNumber(0) - @MaxNumber(32) - @Desc("Load-time box smoothing radius in source pixels") - private int smoothingRadius = 0; - - @MinNumber(0) - @MaxNumber(1) - @Desc("Binary mask threshold") - private double threshold = 0.5D; - - @MinNumber(0) - @MaxNumber(1) - @Desc("Mask transition width above threshold") - private double falloff = 0D; - - @MinNumber(0) - @MaxNumber(MAXIMUM_COLOR_TOLERANCE) - @Desc("Euclidean raw sRGB distance accepted by tolerant color matching; zero is exact") - private double colorTolerance = 0D; - - @Desc("How colors absent from the legend are handled") - private IrisImageMapUnknownColor unknownColor = IrisImageMapUnknownColor.ERROR; - - @Desc("Exact #RRGGBB colors mapped to Iris resource or Minecraft block keys") - private KMap colors = new KMap<>(); - - @Override - public String getFolderName() { - return "image-maps"; - } - - @Override - public String getTypeName() { - return "Image Map"; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapBinding.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapBinding.java deleted file mode 100644 index 395ab2df1..000000000 --- a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapBinding.java +++ /dev/null @@ -1,29 +0,0 @@ -package art.arcane.iris.engine.object.image; - -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.volmlib.util.collection.KList; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@NoArgsConstructor -@Desc("Binds a reusable image map to one dimension generation role") -@Data -public class IrisImageMapBinding { - @Desc("Unique name used by Studio previews and custom map lookups") - private String key = ""; - - @RegistryListResource(IrisImageMap.class) - @Desc("Image-map resource key under image-maps/") - private String map = ""; - - @Desc("Generation input controlled by this binding") - private IrisImageMapApplication application = IrisImageMapApplication.CUSTOM; - - @ArrayType(type = IrisImageMapMask.class) - @Desc("Named mask maps composed in declaration order") - private KList masks = new KList<>(); -} diff --git a/src/main/java/art/arcane/iris/engine/object/material/BlockDataMergeSupport.java b/src/main/java/art/arcane/iris/engine/object/material/BlockDataMergeSupport.java deleted file mode 100644 index 109117b0f..000000000 --- a/src/main/java/art/arcane/iris/engine/object/material/BlockDataMergeSupport.java +++ /dev/null @@ -1,75 +0,0 @@ -package art.arcane.iris.engine.object.material; - -import art.arcane.iris.platform.bukkit.BukkitBlockState; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.platform.bukkit.BukkitBlockResolution; -import org.bukkit.block.data.BlockData; - -import java.util.Objects; -import java.util.function.Function; - -public final class BlockDataMergeSupport { - private static volatile StateMerger PLATFORM_MERGER = null; - - private BlockDataMergeSupport() { - } - - public interface StateMerger { - PlatformBlockState merge(PlatformBlockState base, PlatformBlockState update); - } - - public static synchronized StateMerger bindPlatformMerger(StateMerger merger) { - StateMerger previous = PLATFORM_MERGER; - PLATFORM_MERGER = Objects.requireNonNull(merger, "merger"); - return previous; - } - - public static synchronized void restorePlatformMerger(StateMerger merger) { - PLATFORM_MERGER = merger; - } - - public static PlatformBlockState merge(PlatformBlockState base, PlatformBlockState update) { - StateMerger merger = PLATFORM_MERGER; - if (merger != null) { - return merger.merge(base, update); - } - BlockData merged = merge((BlockData) base.nativeHandle(), (BlockData) update.nativeHandle(), BukkitBlockResolution::get); - return merged == null ? null : BukkitBlockState.of(merged); - } - - static BlockData merge(BlockData base, BlockData update, Function resolver) { - try { - return base.merge(update); - } catch (IllegalArgumentException e) { - BlockData normalizedBase = resolve(base, resolver); - BlockData normalizedUpdate = resolve(update, resolver); - - if (normalizedBase != null && normalizedUpdate != null) { - try { - return normalizedBase.merge(normalizedUpdate); - } catch (IllegalArgumentException ignored) { - return normalizedUpdate; - } - } - - if (normalizedUpdate != null) { - return normalizedUpdate; - } - - return update; - } - } - - private static BlockData resolve(BlockData data, Function resolver) { - if (data == null || resolver == null) { - return null; - } - - String serialized = data.getAsString(false); - if (serialized == null || serialized.isBlank()) { - return null; - } - - return resolver.apply(serialized); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/material/IrisBlockData.java b/src/main/java/art/arcane/iris/engine/object/material/IrisBlockData.java deleted file mode 100644 index dd2e3f4bb..000000000 --- a/src/main/java/art/arcane/iris/engine/object/material/IrisBlockData.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.material; - - -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.core.link.Identifier; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListBlockType; -import art.arcane.iris.engine.object.annotations.RegistryMapBlockState; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.collection.KMap; -import art.arcane.iris.util.common.data.B; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.util.Map; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents Block Data") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisBlockData extends IrisRegistrant { - private final transient AtomicCache blockdata = new AtomicCache<>(); - private final transient AtomicCache realProperties = new AtomicCache<>(); - @RegistryListBlockType - @Required - @Desc("The block to use") - private String block = "air"; - @Desc("Debug this block by printing it to the console when it's used. Must have debug turned on in settings.") - private boolean debug = false; - @MinNumber(1) - @MaxNumber(1000) - @Desc("The weight is used when this block data is inside of a list of blockdata. A weight of two is just as if you placed two of the same block data values in the same list making it more common when randomly picked.") - private int weight = 1; - @Desc("If the block cannot be created on this version, Iris will attempt to use this backup block data instead.") - private IrisBlockData backup = null; - @RegistryMapBlockState("block") - @Desc("Optional properties for this block data such as 'waterlogged': true") - private KMap data = new KMap<>(); - @Desc("Optional tile data for this block data") - private KMap tileData = new KMap<>(); - - public IrisBlockData(String b) { - this.block = b; - } - - public static IrisBlockData from(String j) { - IrisBlockData b = new IrisBlockData(); - String v = j.toLowerCase().trim(); - - if (v.contains("[")) { - KList props = new KList<>(); - String rp = v.split("\\Q[\\E")[1].replaceAll("\\Q]\\E", ""); - b.setBlock(v.split("\\Q[\\E")[0]); - - if (rp.contains(",")) { - props.add(rp.split("\\Q,\\E")); - } else { - props.add(rp); - } - - for (String i : props) { - Object kg = filter(i.split("\\Q=\\E")[1]); - b.data.put(i.split("\\Q=\\E")[0], kg); - } - } else { - b.setBlock(v); - } - - return b; - } - - private static Object filter(String string) { - if (string.equals("true")) { - return true; - } - - if (string.equals("false")) { - return false; - } - - try { - return Integer.parseInt(string); - } catch (Throwable ignored) { - // Checks - } - - try { - return Double.valueOf(string).intValue(); - } catch (Throwable ignored) { - // Checks - } - - return string; - } - - public String computeProperties(KMap data) { - if (data.isEmpty()) { - return ""; - } - - KList r = new KList<>(); - - for (Map.Entry entry : data.entrySet()) { - r.add(entry.getKey() + "=" + filter(entry.getValue().toString())); - } - - return "[" + r.toString(",") + "]"; - } - - public String computeProperties() { - return computeProperties(getData()); - } - - public PlatformBlockState getBlockData(IrisData data) { - return blockdata.aquire(() -> - { - IrisBlockData customData = data.getBlockLoader().load(getBlock(), false); - - if (customData != null) { - PlatformBlockState customState = customData.getBlockData(data); - - if (customState != null) { - String st = customState.key(); - - if (st.contains("[")) { - st = st.split("\\Q[\\E")[0]; - } - - KMap cdata = customData.getData().copy(); - - for (String i : getData().keySet()) { - cdata.put(i, getData().get(i)); - } - - String sx = keyify(st) + computeProperties(cdata); - - if (debug) { - IrisLogging.debug("Block Data used " + sx + " (CUSTOM)"); - } - - PlatformBlockState bx = B.getState(sx); - - if (bx != null) { - return bx; - } - - return customState; - } - } - - String ss = keyify(getBlock()) + computeProperties(); - PlatformBlockState resolved = B.getState(ss); - - if (debug) { - IrisLogging.debug("Block Data used " + ss); - } - - if (resolved != null) { - return resolved; - } - - if (backup != null) { - return backup.getBlockData(data); - } - - return B.getState("AIR"); - }); - } - - public TileData tryGetTile(IrisData data) { - //TODO Do like a registry thing with the tile data registry. Also update the parsing of data to include **block** entities. - PlatformBlockState state = getBlockData(data); - String stateKey = state.key(); - int bracket = stateKey.indexOf('['); - String blockKey = bracket >= 0 ? stateKey.substring(0, bracket) : stateKey; - if (blockKey.equals("minecraft:spawner") && this.data.containsKey("entitySpawn")) { - String id = (String) this.data.get("entitySpawn"); - if (tileData == null) tileData = new KMap<>(); - KMap spawnData = (KMap) tileData.computeIfAbsent("SpawnData", k -> new KMap<>()); - KMap entity = (KMap) spawnData.computeIfAbsent("entity", k -> new KMap<>()); - entity.putIfAbsent("id", Identifier.fromString(id).toString()); - } - - if (tileData == null || tileData.isEmpty() || !state.hasTileEntity()) - return null; - return TileData.of(state, this.tileData); - } - - private String keyify(String dat) { - if (dat.contains(":")) { - return dat; - } - - return "minecraft:" + dat; - } - - @Override - public String getFolderName() { - return "blocks"; - } - - @Override - public String getTypeName() { - return "Block"; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/material/IrisMaterialPalette.java b/src/main/java/art/arcane/iris/engine/object/material/IrisMaterialPalette.java deleted file mode 100644 index 3958db76a..000000000 --- a/src/main/java/art/arcane/iris/engine/object/material/IrisMaterialPalette.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.material; - -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.noise.NoiseStyle; -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.volmlib.util.cache.LazyBoundedCache; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import lombok.AccessLevel; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.experimental.Accessors; - -import java.util.Optional; -import java.util.concurrent.atomic.AtomicReference; - -@Snippet("palette") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A palette of materials") -@Data -public class IrisMaterialPalette { - private static final int LAYER_GENERATOR_CACHE_SIZE = 32; - private static final int LAYER_GENERATOR_SALT = -23_498_896; - - private final transient AtomicCache> blockData = new AtomicCache<>(); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient LazyBoundedCache layerGenerators = - new LazyBoundedCache<>(LAYER_GENERATOR_CACHE_SIZE); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient AtomicReference recentLayerGenerator = new AtomicReference<>(); - private final transient AtomicCache heightGenerator = new AtomicCache<>(); - @Desc("The style of noise") - private IrisGeneratorStyle style = NoiseStyle.STATIC.style(); - @MinNumber(0.0001) - @Desc("The terrain zoom mostly for zooming in on a wispy palette") - private double zoom = 5; - @Required - @ArrayType(min = 1, type = IrisBlockData.class) - @Desc("The palette of blocks to be used in this layer") - private KList palette = new KList().qadd(new IrisBlockData("STONE")); - - public PlatformBlockState get(RNG rng, double x, double y, double z, IrisData rdata) { - KList localBlockData = getBlockData(rdata); - int blockDataSize = localBlockData.size(); - if (blockDataSize == 0) { - return null; - } - - if (blockDataSize == 1) { - return localBlockData.get(0); - } - - double scaledX = x / zoom; - double scaledY = y / zoom; - double scaledZ = z / zoom; - return getLayerGenerator(rng, rdata).fit(localBlockData, scaledX, scaledY, scaledZ); - } - - public Optional getTile(RNG rng, double x, double y, double z, IrisData rdata) { - if (getBlockData(rdata).isEmpty()) - return Optional.empty(); - - TileData tile = getBlockData(rdata).size() == 1 ? palette.get(0).tryGetTile(rdata) : palette.getRandom(rng).tryGetTile(rdata); - return tile != null ? Optional.of(tile) : Optional.empty(); - } - - public CNG getLayerGenerator(RNG rng, IrisData rdata) { - Engine engine = rdata == null ? null : rdata.getEngine(); - int generatorSignature = LAYER_GENERATOR_SALT + getBlockData(rdata).size(); - long generatorSeed = rng.getSeed() + generatorSignature; - CachedLayerGenerator recent = recentLayerGenerator.get(); - if (recent != null && recent.key.matches(rdata, engine, generatorSeed)) { - return recent.generator; - } - - LayerGeneratorKey key = new LayerGeneratorKey(rdata, engine, generatorSeed); - CNG generator = layerGenerators.computeIfAbsent(key, - ignored -> style.create(new RNG(generatorSeed), rdata, engine)); - if (generator != null) { - recentLayerGenerator.set(new CachedLayerGenerator(key, generator)); - } - return generator; - } - - public IrisMaterialPalette qclear() { - palette.clear(); - return this; - } - - public KList add(String b) { - palette.add(new IrisBlockData(b)); - - return palette; - } - - public IrisMaterialPalette qadd(String b) { - palette.add(new IrisBlockData(b)); - - return this; - } - - public KList getBlockData(IrisData rdata) { - return blockData.aquire(() -> - { - KList blockData = new KList<>(); - for (IrisBlockData ix : palette) { - PlatformBlockState bx = ix.getBlockData(rdata); - if (bx != null) { - for (int i = 0; i < ix.getWeight(); i++) { - blockData.add(bx); - } - } - } - - return blockData; - }); - } - - public IrisMaterialPalette zero() { - palette.clear(); - return this; - } - - private static final class LayerGeneratorKey { - private final IrisData data; - private final Engine engine; - private final long seed; - - private LayerGeneratorKey(IrisData data, Engine engine, long seed) { - this.data = data; - this.engine = engine; - this.seed = seed; - } - - private boolean matches(IrisData data, Engine engine, long seed) { - return this.data == data && this.engine == engine && this.seed == seed; - } - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (!(object instanceof LayerGeneratorKey other)) { - return false; - } - return data == other.data && engine == other.engine && seed == other.seed; - } - - @Override - public int hashCode() { - int result = System.identityHashCode(data); - result = 31 * result + System.identityHashCode(engine); - result = 31 * result + Long.hashCode(seed); - return result; - } - } - - private static final class CachedLayerGenerator { - private final LayerGeneratorKey key; - private final CNG generator; - - private CachedLayerGenerator(LayerGeneratorKey key, CNG generator) { - this.key = key; - this.generator = generator; - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/mod/IrisMod.java b/src/main/java/art/arcane/iris/engine/object/mod/IrisMod.java deleted file mode 100644 index e01880283..000000000 --- a/src/main/java/art/arcane/iris/engine/object/mod/IrisMod.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.mod; - -import art.arcane.iris.builtin.blocks.ObjectReplace; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@AllArgsConstructor -@NoArgsConstructor -@Desc("Represents a pack modification schema") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisMod extends IrisRegistrant { - @MinNumber(2) - @Required - @Desc("The human-readable name of this pack modification") - private String name = "A Pack Modification"; - - @Desc("The optional dimension load key this modification targets. An empty value does not restrict the target.") - private String forDimension = ""; - - @MinNumber(-1) - @MaxNumber(512) - @Desc("Override the fluid height. Otherwise set it to -1") - private int overrideFluidHeight = -1; - - @Desc("A list of biomes to remove") - @RegistryListResource(IrisBiome.class) - @ArrayType(type = String.class, min = 1) - private KList removeBiomes = new KList<>(); - - @Desc("A list of objects to remove") - @RegistryListResource(IrisObject.class) - @ArrayType(type = String.class, min = 1) - private KList removeObjects = new KList<>(); - - @Desc("A list of regions to remove") - @RegistryListResource(IrisRegion.class) - @ArrayType(type = String.class, min = 1) - private KList removeRegions = new KList<>(); - - @Desc("A list of regions to inject") - @RegistryListResource(IrisRegion.class) - @ArrayType(type = String.class, min = 1) - private KList injectRegions = new KList<>(); - - @ArrayType(min = 1, type = IrisModBiomeInjector.class) - @Desc("Inject biomes into existing regions") - private KList biomeInjectors = new KList<>(); - - @ArrayType(min = 1, type = IrisModBiomeReplacer.class) - @Desc("Replace biomes with other biomes") - private KList biomeReplacers = new KList<>(); - - @ArrayType(min = 1, type = IrisModObjectReplacer.class) - @Desc("Replace objects with other objects") - private KList objectReplacers = new KList<>(); - - @ArrayType(min = 1, type = IrisModObjectPlacementBiomeInjector.class) - @Desc("Inject placers into existing biomes") - private KList biomeObjectPlacementInjectors = new KList<>(); - - @ArrayType(min = 1, type = IrisModObjectPlacementRegionInjector.class) - @Desc("Inject placers into existing regions") - private KList regionObjectPlacementInjectors = new KList<>(); - - @ArrayType(min = 1, type = IrisModRegionReplacer.class) - @Desc("Replace regions with other regions") - private KList regionReplacers = new KList<>(); - - @ArrayType(min = 1, type = ObjectReplace.class) - @Desc("Replace blocks with other blocks") - private KList blockReplacers = new KList<>(); - - @ArrayType(min = 1, type = IrisModNoiseStyleReplacer.class) - @Desc("Replace noise styles with other styles") - private KList styleReplacers = new KList<>(); - - @Override - public String getFolderName() { - return "mods"; - } - - @Override - public String getTypeName() { - return "Mod"; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/mod/IrisModBiomeInjector.java b/src/main/java/art/arcane/iris/engine/object/mod/IrisModBiomeInjector.java deleted file mode 100644 index 2488a6987..000000000 --- a/src/main/java/art/arcane/iris/engine/object/mod/IrisModBiomeInjector.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.mod; - -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("biome-injector") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A biome injector") -@Data -public class IrisModBiomeInjector { - @Required - @Desc("The region to find") - @RegistryListResource(IrisRegion.class) - private String region = ""; - - @Required - @Desc("A biome to inject into the region") - @RegistryListResource(IrisBiome.class) - @ArrayType(type = String.class, min = 1) - private KList inject = new KList<>(); -} diff --git a/src/main/java/art/arcane/iris/engine/object/mod/IrisModBiomeReplacer.java b/src/main/java/art/arcane/iris/engine/object/mod/IrisModBiomeReplacer.java deleted file mode 100644 index 3a1553c4a..000000000 --- a/src/main/java/art/arcane/iris/engine/object/mod/IrisModBiomeReplacer.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.mod; - -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("biome-replacer") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A biome replacer") -@Data -public class IrisModBiomeReplacer { - @Required - @Desc("A list of biomes to find") - @RegistryListResource(IrisBiome.class) - @ArrayType(type = String.class, min = 1) - private KList find = new KList<>(); - - @Required - @Desc("A biome to replace it with") - @RegistryListResource(IrisBiome.class) - private String replace = ""; -} diff --git a/src/main/java/art/arcane/iris/engine/object/mod/IrisModNoiseStyleReplacer.java b/src/main/java/art/arcane/iris/engine/object/mod/IrisModNoiseStyleReplacer.java deleted file mode 100644 index ec251a343..000000000 --- a/src/main/java/art/arcane/iris/engine/object/mod/IrisModNoiseStyleReplacer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.mod; - -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.noise.NoiseStyle; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("noise-style-replacer") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A noise style replacer") -@Data -public class IrisModNoiseStyleReplacer { - @Required - @Desc("A noise style to find") - private NoiseStyle find = NoiseStyle.IRIS; - - @Required - @Desc("If replaceTypeOnly is set to true, Iris will keep the existing generator style and only replace the type itself. Otherwise it will use the replace tag for every style using the find type.") - private boolean replaceTypeOnly = false; - - @Required - @Desc("A noise style to replace it with") - private IrisGeneratorStyle replace = new IrisGeneratorStyle(); -} diff --git a/src/main/java/art/arcane/iris/engine/object/mod/IrisModObjectPlacementBiomeInjector.java b/src/main/java/art/arcane/iris/engine/object/mod/IrisModObjectPlacementBiomeInjector.java deleted file mode 100644 index aaa0c4fe2..000000000 --- a/src/main/java/art/arcane/iris/engine/object/mod/IrisModObjectPlacementBiomeInjector.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.mod; - -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("object-placement-biome-injector") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("An object placement injector") -@Data -public class IrisModObjectPlacementBiomeInjector { - @Required - @Desc("The biome to find") - @RegistryListResource(IrisBiome.class) - private String biome = ""; - - @Required - @Desc("Object placements to inject into the biome") - @ArrayType(type = IrisObjectPlacement.class, min = 1) - private KList place = new KList<>(); -} diff --git a/src/main/java/art/arcane/iris/engine/object/mod/IrisModObjectPlacementRegionInjector.java b/src/main/java/art/arcane/iris/engine/object/mod/IrisModObjectPlacementRegionInjector.java deleted file mode 100644 index 0fe2601f2..000000000 --- a/src/main/java/art/arcane/iris/engine/object/mod/IrisModObjectPlacementRegionInjector.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.mod; - -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("object-placement-region-injector") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("An object placement injector") -@Data -public class IrisModObjectPlacementRegionInjector { - @Required - @Desc("The region to find") - @RegistryListResource(IrisRegion.class) - private String biome = ""; - - @Required - @Desc("Object placements to inject into the region") - @ArrayType(type = IrisObjectPlacement.class, min = 1) - private KList place = new KList<>(); -} diff --git a/src/main/java/art/arcane/iris/engine/object/mod/IrisModObjectReplacer.java b/src/main/java/art/arcane/iris/engine/object/mod/IrisModObjectReplacer.java deleted file mode 100644 index b4893f272..000000000 --- a/src/main/java/art/arcane/iris/engine/object/mod/IrisModObjectReplacer.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.mod; - -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("object-replacer") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("An object replacer") -@Data -public class IrisModObjectReplacer { - @Required - @Desc("A list of objects to find") - @RegistryListResource(IrisObject.class) - @ArrayType(type = String.class, min = 1) - private KList find = new KList<>(); - - @Required - @Desc("An object to replace it with") - @RegistryListResource(IrisObject.class) - private String replace = ""; -} diff --git a/src/main/java/art/arcane/iris/engine/object/mod/IrisModRegionReplacer.java b/src/main/java/art/arcane/iris/engine/object/mod/IrisModRegionReplacer.java deleted file mode 100644 index c8088ce8a..000000000 --- a/src/main/java/art/arcane/iris/engine/object/mod/IrisModRegionReplacer.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.mod; - -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("region-replacer") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A region replacer") -@Data -public class IrisModRegionReplacer { - @Required - @Desc("A list of regions to find") - @RegistryListResource(IrisRegion.class) - @ArrayType(type = String.class, min = 1) - private KList find = new KList<>(); - - @Required - @Desc("A region to replace it with") - @RegistryListResource(IrisRegion.class) - private String replace = ""; -} diff --git a/src/main/java/art/arcane/iris/engine/object/noise/IrisGeneratorStyle.java b/src/main/java/art/arcane/iris/engine/object/noise/IrisGeneratorStyle.java deleted file mode 100644 index 4a435a604..000000000 --- a/src/main/java/art/arcane/iris/engine/object/noise/IrisGeneratorStyle.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.noise; - -import art.arcane.iris.engine.object.image.IrisImageMap; -import art.arcane.iris.engine.object.noise.expression.IrisExpression; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.volmlib.util.cache.LazyBoundedCache; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.iris.util.project.noise.ExpressionNoise; -import art.arcane.iris.util.project.noise.ImageNoise; -import lombok.AccessLevel; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.experimental.Accessors; - -import java.io.File; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; - -@Snippet("style") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A gen style") -@Data -public class IrisGeneratorStyle { - private static final int GENERATOR_CACHE_SIZE = 8; - private static final ConcurrentHashMap ACTIVE_CACHE_KEYS = new ConcurrentHashMap<>(); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient LazyBoundedCache generatorCache = - new LazyBoundedCache<>(GENERATOR_CACHE_SIZE); - @Desc("The base noise style. Used when neither expression nor imageMap is set; a failed expression also falls back to this style.") - private NoiseStyle style = NoiseStyle.FLAT; - - @Desc("If set above 0, this style will be cellularized") - private double cellularFrequency = 0; - - @Desc("Cell zooms") - private double cellularZoom = 1; - @MinNumber(0.00001) - @Desc("The zoom of this style") - private double zoom = 1; - @Desc("Instead of using the style property, use a custom expression to represent this style.") - @RegistryListResource(IrisExpression.class) - private String expression = null; - @Desc("Use an Image map instead of a generated value") - @RegistryListResource(IrisImageMap.class) - private String imageMap = null; - @MinNumber(0.00001) - @Desc("The Output multiplier. Only used if parent is fracture.") - private double multiplier = 1; - @Desc("Apply a generator to the coordinate field fed into this parent generator. I.e. Distort your generator with another generator.") - private IrisGeneratorStyle fracture = null; - @MinNumber(0.01562) - @MaxNumber(64) - @Desc("The exponent") - private double exponent = 1; - @MinNumber(0) - @MaxNumber(8192) - @Desc("If the cache size is set above 0, this generator will be cached") - private int cacheSize = 0; - - public IrisGeneratorStyle(NoiseStyle s) { - this.style = s; - } - - public IrisGeneratorStyle zoomed(double z) { - this.zoom = z; - return this; - } - - public CNG createNoCache(RNG rng, IrisData data) { - return createNoCache(rng, data, false, 0, false, resolveEngine(data)); - } - - public CNG createForPrebake(RNG rng, IrisData data, int fallbackCacheSize) { - return createNoCache(rng, data, false, Math.max(0, fallbackCacheSize), true, resolveEngine(data)); - } - - - private int imageMapHash() { - if (imageMap == null) { - return 0; - } - - return imageMap.hashCode(); - } - - private int hash() { - return Objects.hash(expression, imageMapHash(), multiplier, fracture != null ? fracture.hash() : 0, exponent, cacheSize, zoom, cellularZoom, cellularFrequency, style); - } - - public int prebakeSignature() { - return hash(); - } - - private String cachePrefix(RNG rng, int effectiveCacheSize, long engineStamp) { - return "style-" + Integer.toUnsignedString(hash()) - + "-seed-" + Long.toUnsignedString(rng.getSeed()) - + "-eng-" + Long.toUnsignedString(engineStamp) - + "-sz-" + effectiveCacheSize - + "-src-"; - } - - private String cacheKey(RNG rng, long sourceStamp, int effectiveCacheSize, long engineStamp) { - return cachePrefix(rng, effectiveCacheSize, engineStamp) + Long.toUnsignedString(sourceStamp); - } - - private void clearStaleCacheEntries(IrisData data, String prefix, String key) { - File cacheFolder = new File(data.getDataFolder(), ".cache"); - String cacheFolderKey = cacheFolder.getAbsolutePath() + File.separator + prefix; - String previousKey = ACTIVE_CACHE_KEYS.put(cacheFolderKey, key); - if (key.equals(previousKey)) { - return; - } - File[] files = cacheFolder.listFiles((dir, name) -> name.endsWith(".cnm") && name.startsWith(prefix)); - if (files == null) { - return; - } - - String keepFile = key + ".cnm"; - for (File file : files) { - if (keepFile.equals(file.getName())) { - continue; - } - - if (!file.delete()) { - IrisLogging.debug("Unable to delete stale noise cache " + file.getName()); - } - } - } - - public CNG createNoCache(RNG rng, IrisData data, boolean actuallyCached) { - return createNoCache(rng, data, actuallyCached, 0, false, resolveEngine(data)); - } - - private CNG createNoCache(RNG rng, IrisData data, boolean actuallyCached, int fallbackCacheSize, - boolean quietCacheLog, Engine engine) { - CNG cng = null; - long sourceStamp = 0L; - if (getExpression() != null) { - IrisExpression e = data.getExpressionLoader().load(getExpression()); - if (e != null) { - cng = new CNG(rng, new ExpressionNoise(rng, e), 1D, 1).bake(); - sourceStamp = Integer.toUnsignedLong(Objects.hash(getExpression(), - e.getLoadFile() == null ? 0L : e.getLoadFile().lastModified())); - } - } else if (getImageMap() != null) { - ImageNoise imageNoise = new ImageNoise(data, getImageMap()); - cng = new CNG(rng, imageNoise, 1D, 1).bake(); - sourceStamp = Integer.toUnsignedLong(imageNoise.getContentHash().hashCode()); - } - - if (cng == null) { - cng = (style != null ? style : NoiseStyle.FLAT).create(rng).bake(); - } - - cng = cng.scale(1D / zoom).pow(exponent).bake(); - - if (fracture != null) { - cng.fractureWith(fracture.createNoCache(rng.nextParallelRNG(2934), data, false, - fallbackCacheSize, quietCacheLog, engine), fracture.getMultiplier()); - } - - if (cellularFrequency > 0) { - cng = cng.cellularize(rng.nextParallelRNG(884466), cellularFrequency).scale(1D / cellularZoom).bake(); - } - - int effectiveCacheSize = cacheSize > 0 ? cacheSize : Math.max(0, fallbackCacheSize); - if (effectiveCacheSize > 0) { - long engineStamp = engineStamp(engine); - String key = cacheKey(rng, sourceStamp, effectiveCacheSize, engineStamp); - clearStaleCacheEntries(data, cachePrefix(rng, effectiveCacheSize, engineStamp), key); - cng = cng.cached(effectiveCacheSize, key, data.getDataFolder(), quietCacheLog); - } - - return cng; - } - - public double warp(RNG rng, IrisData data, double value, double... coords) { - return create(rng, data).noise(coords) + value; - } - - public CNG create(RNG rng, IrisData data) { - return create(rng, data, resolveEngine(data)); - } - - public CNG create(RNG rng, IrisData data, Engine engine) { - GeneratorCacheKey key = new GeneratorCacheKey(data, engine, rng.getSeed()); - return generatorCache.computeIfAbsent(key, - ignored -> createNoCache(rng, data, true, 0, false, engine)); - } - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean isFlat() { - return style == null || style.equals(NoiseStyle.FLAT); - } - - public double getMaxFractureDistance() { - return multiplier; - } - - private long engineStamp(Engine engine) { - if (engine == null) { - return 0L; - } - return Integer.toUnsignedLong(Objects.hash( - engine.getSeedManager().getSeed(), - engine.getMinHeight(), - engine.getMaxHeight(), - engine.getDimension().getLoadKey(), - engine.getDimension().getFluidHeight() - )); - } - - private Engine resolveEngine(IrisData data) { - return data == null ? null : data.getEngine(); - } - - private static final class GeneratorCacheKey { - private final IrisData data; - private final Engine engine; - private final long seed; - - private GeneratorCacheKey(IrisData data, Engine engine, long seed) { - this.data = data; - this.engine = engine; - this.seed = seed; - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof GeneratorCacheKey key)) { - return false; - } - return data == key.data && engine == key.engine && seed == key.seed; - } - - @Override - public int hashCode() { - int result = System.identityHashCode(data); - result = 31 * result + System.identityHashCode(engine); - return 31 * result + Long.hashCode(seed); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/noise/IrisInterpolator.java b/src/main/java/art/arcane/iris/engine/object/noise/IrisInterpolator.java deleted file mode 100644 index deaf94468..000000000 --- a/src/main/java/art/arcane/iris/engine/object/noise/IrisInterpolator.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.noise; - -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.volmlib.util.function.NoiseProvider; -import art.arcane.iris.util.project.interpolation.InterpolationMethod; -import art.arcane.iris.util.project.interpolation.IrisInterpolation; -import art.arcane.iris.util.project.interpolation.NoiseBounds; -import art.arcane.iris.util.project.interpolation.NoiseBoundsProvider; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Configures rotation for iris") -@Data -public class IrisInterpolator { - public static final IrisInterpolator DEFAULT = new IrisInterpolator(); - - @Required - @Desc("The interpolation method when two biomes use different heights but this same generator") - private InterpolationMethod function = InterpolationMethod.BILINEAR_STARCAST_6; - - @Required - @MinNumber(1) - @MaxNumber(8192) - @Desc("The range checked horizontally. Smaller ranges yeild more detail but are not as smooth.") - private double horizontalScale = 7; - - @Override - public int hashCode() { - // Bit-identical to Objects.hash(horizontalScale, function) without the Object[] or Double boxing. - int result = 31 + Double.hashCode(horizontalScale); - return (31 * result) + (function == null ? 0 : function.hashCode()); - } - - @Override - public boolean equals(Object o) { - if (o instanceof IrisInterpolator i) { - return i.getFunction().equals(function) && i.getHorizontalScale() == horizontalScale; - } - - return false; - } - - public double interpolate(double x, double z, NoiseProvider provider) { - return interpolate((int) Math.round(x), (int) Math.round(z), provider); - } - - public double interpolate(int x, int z, NoiseProvider provider) { - return IrisInterpolation.getNoise(getFunction(), x, z, getHorizontalScale(), provider); - } - - public NoiseBounds interpolateBounds(double x, double z, NoiseBoundsProvider provider) { - return interpolateBounds((int) Math.round(x), (int) Math.round(z), provider); - } - - public NoiseBounds interpolateBounds(int x, int z, NoiseBoundsProvider provider) { - return IrisInterpolation.getNoiseBounds(getFunction(), x, z, getHorizontalScale(), provider); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/noise/IrisNoiseGenerator.java b/src/main/java/art/arcane/iris/engine/object/noise/IrisNoiseGenerator.java deleted file mode 100644 index 8dd8c8f9d..000000000 --- a/src/main/java/art/arcane/iris/engine/object/noise/IrisNoiseGenerator.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.noise; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.volmlib.util.cache.LazyBoundedCache; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.util.project.interpolation.IrisInterpolation; -import art.arcane.iris.util.project.noise.CNG; -import lombok.AccessLevel; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.experimental.Accessors; - -import java.util.concurrent.atomic.AtomicReference; - -@Snippet("generator") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A noise generator") -@Data -public class IrisNoiseGenerator { - private static final int GENERATOR_CACHE_SIZE = 32; - private static final long GENERATOR_SEED_SALT = 33_955_677L; - - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient LazyBoundedCache generators = - new LazyBoundedCache<>(GENERATOR_CACHE_SIZE); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient AtomicReference recentGenerator = new AtomicReference<>(); - @MinNumber(0.0001) - @Desc("The coordinate input zoom") - private double zoom = 1; - @Desc("Reverse the output. So that noise = -noise + opacity") - private boolean negative = false; - @MinNumber(0) - @MaxNumber(1) - @Desc("The output multiplier") - private double opacity = 1; - @Desc("Coordinate offset x") - private double offsetX = 0; - @Desc("Height output offset y. Avoid using with terrain generation.") - private double offsetY = 0; - @Desc("Coordinate offset z") - private double offsetZ = 0; - @Required - @Desc("The seed") - private long seed = 0; - @Desc("Apply a parametric curve on the output") - private boolean parametric = false; - @Desc("Apply a bezier curve on the output") - private boolean bezier = false; - @Desc("Apply a sin-center curve on the output (0, and 1 = 0 and 0.5 = 1.0 using a sinoid shape.)") - private boolean sinCentered = false; - @Desc("The exponent noise^EXPONENT") - private double exponent = 1; - @Desc("Enable / disable. Outputs offsetY if disabled") - private boolean enabled = true; - @Required - @Desc("The Noise Style") - private IrisGeneratorStyle style = NoiseStyle.IRIS.style(); - @MinNumber(1) - @Desc("Multiple octaves for multple generators of changing zooms added together") - private int octaves = 1; - @ArrayType(min = 1, type = IrisNoiseGenerator.class) - @Desc("Apply a child noise generator to fracture the input coordinates of this generator") - private KList fracture = new KList<>(); - - public IrisNoiseGenerator(boolean enabled) { - this(); - this.enabled = enabled; - } - - protected CNG getGenerator(long superSeed, IrisData data) { - Engine engine = data == null ? null : data.getEngine(); - long generatorSeed = superSeed + GENERATOR_SEED_SALT - seed; - CachedGenerator recent = recentGenerator.get(); - if (recent != null && recent.key.matches(data, engine, generatorSeed)) { - return recent.generator; - } - - GeneratorKey key = new GeneratorKey(data, engine, generatorSeed); - CNG generator = generators.computeIfAbsent(key, - ignored -> style.createNoCache(new RNG(generatorSeed), data).oct(octaves)); - if (generator != null) { - recentGenerator.set(new CachedGenerator(key, generator)); - } - return generator; - } - - public double getMax() { - return getOffsetY() + opacity; - } - - public double getNoise(long superSeed, double xv, double zv, IrisData data) { - if (!enabled) { - return offsetY; - } - - double x = xv; - double z = zv; - int g = 33; - - for (IrisNoiseGenerator i : fracture) { - if (i.isEnabled()) { - double fractureOffset = i.getOpacity() / 2D; - x += i.getNoise(superSeed + seed + g, xv, zv, data) - fractureOffset; - z += i.getNoise(superSeed + seed + g, zv, xv, data) - fractureOffset; - } - g += 819; - } - - CNG cng = getGenerator(superSeed, data); - double sampleX = (x / zoom) + offsetX; - double sampleZ = (z / zoom) + offsetZ; - double n = cng.noiseFast2D(sampleX, sampleZ) * opacity; - n = negative ? (-n + opacity) : n; - n = (exponent != 1 ? n < 0 ? -Math.pow(-n, exponent) : Math.pow(n, exponent) : n) + offsetY; - n = parametric ? IrisInterpolation.parametric(n, 1) : n; - n = bezier ? IrisInterpolation.bezier(n) : n; - n = sinCentered ? IrisInterpolation.sinCenter(n) : n; - - return n; - } - - public KList getAllComposites() { - KList g = new KList<>(); - - g.add(this); - - for (IrisNoiseGenerator i : getFracture()) { - g.addAll(i.getAllComposites()); - } - - return g; - } - - private static final class GeneratorKey { - private final IrisData data; - private final Engine engine; - private final long seed; - - private GeneratorKey(IrisData data, Engine engine, long seed) { - this.data = data; - this.engine = engine; - this.seed = seed; - } - - private boolean matches(IrisData data, Engine engine, long seed) { - return this.data == data && this.engine == engine && this.seed == seed; - } - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (!(object instanceof GeneratorKey other)) { - return false; - } - return data == other.data && engine == other.engine && seed == other.seed; - } - - @Override - public int hashCode() { - int result = System.identityHashCode(data); - result = 31 * result + System.identityHashCode(engine); - result = 31 * result + Long.hashCode(seed); - return result; - } - } - - private static final class CachedGenerator { - private final GeneratorKey key; - private final CNG generator; - - private CachedGenerator(GeneratorKey key, CNG generator) { - this.key = key; - this.generator = generator; - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/noise/IrisShapedGeneratorStyle.java b/src/main/java/art/arcane/iris/engine/object/noise/IrisShapedGeneratorStyle.java deleted file mode 100644 index ce23ad862..000000000 --- a/src/main/java/art/arcane/iris/engine/object/noise/IrisShapedGeneratorStyle.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.noise; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("shaped-style") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("This represents a generator with a min and max height") -@Data -public class IrisShapedGeneratorStyle { - @Required - @Desc("The generator id") - private IrisGeneratorStyle generator = new IrisGeneratorStyle(NoiseStyle.IRIS); - - @Required - @MinNumber(-2032) - @MaxNumber(2032) - @Desc("The min block value") - private int min = 0; - - @Required - @MinNumber(-2032) - @MaxNumber(2032) - @Desc("The max block value") - private int max = 0; - - public IrisShapedGeneratorStyle(NoiseStyle style, int min, int max) { - this(style); - this.min = min; - this.max = max; - } - - public IrisShapedGeneratorStyle(NoiseStyle style) { - this.generator = new IrisGeneratorStyle(style); - } - - public double get(RNG rng, IrisData data, double... dim) { - return generator.create(rng, data).fitDouble(min, max, dim); - } - - public double get(RNG rng, IrisData data, double x, double z) { - return generator.create(rng, data).fitDouble(min, max, x, z); - } - - public double get(RNG rng, IrisData data, double x, double y, double z) { - return generator.create(rng, data).fitDouble(min, max, x, y, z); - } - - public boolean isFlat() { - return min == max || getGenerator().isFlat(); - } - - public int getMid() { - return (getMax() + getMin()) / 2; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/noise/IrisStyledRange.java b/src/main/java/art/arcane/iris/engine/object/noise/IrisStyledRange.java deleted file mode 100644 index 4ac0beb53..000000000 --- a/src/main/java/art/arcane/iris/engine/object/noise/IrisStyledRange.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.noise; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.math.M; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.util.project.stream.ProceduralStream; -import art.arcane.iris.util.project.stream.interpolation.Interpolated; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("style-range") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a range styled with a custom generator") -@Data -public class IrisStyledRange { - @Desc("The minimum value") - private double min = 16; - - @Desc("The maximum value") - private double max = 32; - - @Desc("The style to pick the range") - private IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.STATIC); - - public double get(RNG rng, double x, double z, IrisData data) { - if (min == max) { - return min; - } - - if (style.isFlat()) { - return M.lerp(min, max, 0.5); - } - - return style.create(rng, data).fitDouble(min, max, x, z); - } - - public ProceduralStream stream(RNG rng, IrisData data) { - return ProceduralStream.of((x, z) -> get(rng, x, z, data), Interpolated.DOUBLE); - } - - public boolean isFlat() { - return getMax() == getMin() || style.isFlat(); - } - - public int getMid() { - return (int) ((getMax() + getMin()) / 2); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/noise/NoiseStyle.java b/src/main/java/art/arcane/iris/engine/object/noise/NoiseStyle.java deleted file mode 100644 index 402bae799..000000000 --- a/src/main/java/art/arcane/iris/engine/object/noise/NoiseStyle.java +++ /dev/null @@ -1,566 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.noise; - -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.iris.util.project.noise.CNGFactory; -import art.arcane.iris.util.project.noise.NoiseType; -import art.arcane.iris.util.project.stream.ProceduralStream; -@Desc("Styles of noise") -public enum NoiseStyle { - @Desc("White Noise is like static. Useful for block scattering but not terrain.") - STATIC(rng -> new CNG(rng, NoiseType.WHITE, 1D, 1)), - - @Desc("White Noise is like static. Useful for block scattering but not terrain.") - STATIC_BILINEAR(rng -> new CNG(rng, NoiseType.WHITE_BILINEAR, 1D, 1)), - - @Desc("White Noise is like static. Useful for block scattering but not terrain.") - STATIC_BICUBIC(rng -> new CNG(rng, NoiseType.WHITE_BICUBIC, 1D, 1)), - - @Desc("White Noise is like static. Useful for block scattering but not terrain.") - STATIC_HERMITE(rng -> new CNG(rng, NoiseType.WHITE_HERMITE, 1D, 1)), - - @Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.") - IRIS(rng -> CNG.signature(rng).scale(1)), - - @Desc("Clover Noise") - CLOVER(rng -> new CNG(rng, NoiseType.CLOVER, 1D, 1).scale(0.06).bake()), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_STARCAST_3(rng -> new CNG(rng, NoiseType.CLOVER_STARCAST_3, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_STARCAST_6(rng -> new CNG(rng, NoiseType.CLOVER_STARCAST_6, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_STARCAST_9(rng -> new CNG(rng, NoiseType.CLOVER_STARCAST_9, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_STARCAST_12(rng -> new CNG(rng, NoiseType.CLOVER_STARCAST_12, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_BILINEAR_STARCAST_3(rng -> new CNG(rng, NoiseType.CLOVER_BILINEAR_STARCAST_3, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_BILINEAR_STARCAST_6(rng -> new CNG(rng, NoiseType.CLOVER_BILINEAR_STARCAST_6, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_BILINEAR_STARCAST_9(rng -> new CNG(rng, NoiseType.CLOVER_BILINEAR_STARCAST_9, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_BILINEAR_STARCAST_12(rng -> new CNG(rng, NoiseType.CLOVER_BILINEAR_STARCAST_12, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_HERMITE_STARCAST_3(rng -> new CNG(rng, NoiseType.CLOVER_HERMITE_STARCAST_3, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_HERMITE_STARCAST_6(rng -> new CNG(rng, NoiseType.CLOVER_HERMITE_STARCAST_6, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_HERMITE_STARCAST_9(rng -> new CNG(rng, NoiseType.CLOVER_HERMITE_STARCAST_9, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_HERMITE_STARCAST_12(rng -> new CNG(rng, NoiseType.CLOVER_HERMITE_STARCAST_12, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_BILINEAR(rng -> new CNG(rng, NoiseType.CLOVER_BILINEAR, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_BICUBIC(rng -> new CNG(rng, NoiseType.CLOVER_BICUBIC, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_HERMITE(rng -> new CNG(rng, NoiseType.CLOVER_HERMITE, 1D, 1)), - - @Desc("Vascular noise gets higher as the position nears a cell border.") - VASCULAR(rng -> new CNG(rng, NoiseType.VASCULAR, 1D, 1)), - - @Desc("It always returns 0.5") - FLAT(rng -> new CNG(rng, NoiseType.FLAT, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR(rng -> new CNG(rng, NoiseType.CELLULAR, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_STARCAST_3(rng -> new CNG(rng, NoiseType.CELLULAR_STARCAST_3, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_STARCAST_6(rng -> new CNG(rng, NoiseType.CELLULAR_STARCAST_6, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_STARCAST_9(rng -> new CNG(rng, NoiseType.CELLULAR_STARCAST_9, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_STARCAST_12(rng -> new CNG(rng, NoiseType.CELLULAR_STARCAST_12, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_BILINEAR_STARCAST_3(rng -> new CNG(rng, NoiseType.CELLULAR_BILINEAR_STARCAST_3, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_BILINEAR_STARCAST_6(rng -> new CNG(rng, NoiseType.CELLULAR_BILINEAR_STARCAST_6, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_BILINEAR_STARCAST_9(rng -> new CNG(rng, NoiseType.CELLULAR_BILINEAR_STARCAST_9, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_BILINEAR_STARCAST_12(rng -> new CNG(rng, NoiseType.CELLULAR_BILINEAR_STARCAST_12, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_HERMITE_STARCAST_3(rng -> new CNG(rng, NoiseType.CELLULAR_HERMITE_STARCAST_3, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_HERMITE_STARCAST_6(rng -> new CNG(rng, NoiseType.CELLULAR_HERMITE_STARCAST_6, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_HERMITE_STARCAST_9(rng -> new CNG(rng, NoiseType.CELLULAR_HERMITE_STARCAST_9, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_HERMITE_STARCAST_12(rng -> new CNG(rng, NoiseType.CELLULAR_HERMITE_STARCAST_12, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_BILINEAR(rng -> new CNG(rng, NoiseType.CELLULAR_BILINEAR, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_BICUBIC(rng -> new CNG(rng, NoiseType.CELLULAR_BICUBIC, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_HERMITE(rng -> new CNG(rng, NoiseType.CELLULAR_HERMITE, 1D, 1)), - - @Desc("Hexagonal cells with stable per-cell values.") - HEXAGON(rng -> new CNG(rng, NoiseType.HEXAGON, 1D, 1).scale(1)), - - @Desc("Hex James substitution pattern with 3 large and 3 small recursive hex children plus gaps.") - HEX_JAMES(rng -> new CNG(rng, NoiseType.HEX_JAMES, 1D, 1).scale(1)), - - @Desc("Interlocked solid hex cells with per-cell values from a smooth simplex heatmap.") - HEX_SIMPLEX(rng -> new CNG(rng, NoiseType.HEX_SIMPLEX, 1D, 1).scale(1)), - - @Desc("Randomized finite-depth Sierpinski-style hex recursion with per-level random 3-large/3-small James substitution.") - HEX_RANDOM_SIZE(rng -> new CNG(rng, NoiseType.HEX_RANDOM_SIZE, 1D, 1).scale(1)), - - @Desc("Sierpinski triangle mask blended with simplex heat.") - SIERPINSKI_TRIANGLE(rng -> new CNG(rng, NoiseType.SIERPINSKI_TRIANGLE, 1D, 1).scale(1)), - - @Desc("Classic German Engineering") - NOWHERE(rng -> CNG.signaturePerlin(rng).scale(0.776).bake()), - - @Desc("Classic German Engineering") - NOWHERE_CELLULAR(rng -> CNG.signaturePerlin(rng, NoiseType.CELLULAR).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_CLOVER(rng -> CNG.signaturePerlin(rng, NoiseType.CLOVER).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_HEXAGON(rng -> CNG.signaturePerlin(rng, NoiseType.HEXAGON).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_HEX_JAMES(rng -> CNG.signaturePerlin(rng, NoiseType.HEX_JAMES).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_HEX_SIMPLEX(rng -> CNG.signaturePerlin(rng, NoiseType.HEX_SIMPLEX).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_HEX_RANDOM_SIZE(rng -> CNG.signaturePerlin(rng, NoiseType.HEX_RANDOM_SIZE).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_SIERPINSKI_TRIANGLE(rng -> CNG.signaturePerlin(rng, NoiseType.SIERPINSKI_TRIANGLE).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_SIMPLEX(rng -> CNG.signaturePerlin(rng, NoiseType.SIMPLEX).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_GLOB(rng -> CNG.signaturePerlin(rng, NoiseType.GLOB).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_VASCULAR(rng -> CNG.signaturePerlin(rng, NoiseType.VASCULAR).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_CUBIC(rng -> CNG.signaturePerlin(rng, NoiseType.CUBIC).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_SUPERFRACTAL(rng -> CNG.signaturePerlin(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_FRACTAL(rng -> CNG.signaturePerlin(rng, NoiseType.FRACTAL_BILLOW_PERLIN).scale(1).bake()), - - @Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.") - IRIS_DOUBLE(rng -> CNG.signatureDouble(rng).scale(1)), - - @Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.") - IRIS_THICK(rng -> CNG.signatureThick(rng).scale(1)), - - @Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.") - IRIS_HALF(rng -> CNG.signatureHalf(rng).scale(1)), - - @Desc("Basic, Smooth & Fast Simplex noise.") - SIMPLEX(rng -> new CNG(rng, 1D, 1).scale(1)), - - @Desc("Very Detailed smoke using simplex fractured with fractal billow simplex at high octaves.") - FRACTAL_SMOKE(rng -> new CNG(rng, 1D, 1).fractureWith(new CNG(rng.nextParallelRNG(1), NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 8).scale(0.2), 1000).scale(0.34)), - - @Desc("Thinner Veins.") - VASCULAR_THIN(rng -> new CNG(rng.nextParallelRNG(1), NoiseType.VASCULAR, 1D, 1).scale(1).pow(0.65)), - - @Desc("Cells of simplex noise") - SIMPLEX_CELLS(rng -> new CNG(rng.nextParallelRNG(1), NoiseType.SIMPLEX, 1D, 1).scale(1).fractureWith(new CNG(rng.nextParallelRNG(8), NoiseType.CELLULAR, 1D, 1).scale(1), 200)), - - @Desc("Veins of simplex noise") - SIMPLEX_VASCULAR(rng -> new CNG(rng.nextParallelRNG(1), NoiseType.SIMPLEX, 1D, 1).scale(1).fractureWith(new CNG(rng.nextParallelRNG(8), NoiseType.VASCULAR, 1D, 1).scale(1), 200)), - - @Desc("Very Detailed fluid using simplex fractured with fractal billow simplex at high octaves.") - FRACTAL_WATER(rng -> new CNG(rng, 1D, 1).fractureWith(new CNG(rng.nextParallelRNG(1), NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 9).scale(0.03), 9900).scale(1.14)), - - @Desc("Perlin. Like simplex but more natural") - PERLIN(rng -> new CNG(rng, NoiseType.PERLIN, 1D, 1).scale(1.15)), - - @Desc("Perlin. Like simplex but more natural") - PERLIN_IRIS(rng -> CNG.signature(rng, NoiseType.PERLIN).scale(1.47)), - - @Desc("Perlin. Like simplex but more natural") - PERLIN_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.PERLIN).scale(1.47)), - - @Desc("Perlin. Like simplex but more natural") - PERLIN_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.PERLIN).scale(1.47)), - - @Desc("Perlin. Like simplex but more natural") - PERLIN_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.PERLIN).scale(1.47)), - - @Desc("Billow Fractal Perlin Noise.") - FRACTAL_BILLOW_PERLIN(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_PERLIN, 1D, 1).scale(1.47)), - - @Desc("Billow Fractal Perlin Noise. 2 Octaves") - BIOCTAVE_FRACTAL_BILLOW_PERLIN(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_PERLIN, 1D, 2).scale(1.17)), - - @Desc("Billow Fractal Simplex Noise. Single octave.") - FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 1)), - - @Desc("FBM Fractal Simplex Noise. Single octave.") - FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 1)), - - @Desc("Billow Fractal Iris Noise. Single octave.") - FRACTAL_BILLOW_IRIS(rng -> CNG.signature(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX)), - - @Desc("FBM Fractal Iris Noise. Single octave.") - FRACTAL_FBM_IRIS(rng -> CNG.signature(rng, NoiseType.FRACTAL_FBM_SIMPLEX)), - - @Desc("Billow Fractal Iris Noise. Single octave.") - FRACTAL_BILLOW_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX)), - - @Desc("FBM Fractal Iris Noise. Single octave.") - FRACTAL_FBM_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.FRACTAL_FBM_SIMPLEX)), - - @Desc("Billow Fractal Iris Noise. Single octave.") - FRACTAL_BILLOW_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX)), - - @Desc("FBM Fractal Iris Noise. Single octave.") - FRACTAL_FBM_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.FRACTAL_FBM_SIMPLEX)), - - @Desc("Fractal hexagonal cell noise.") - FRACTAL_HEXAGON(rng -> new CNG(rng, NoiseType.HEXAGON, 1D, 4).scale(1)), - - @Desc("Fractal Hex James substitution pattern with recursive 3-large/3-small child hexes and gaps.") - FRACTAL_HEX_JAMES(rng -> new CNG(rng, NoiseType.HEX_JAMES, 1D, 4).scale(1)), - - @Desc("Interlocked solid hex cells with per-cell fractal simplex heatmap values.") - FRACTAL_HEX_SIMPLEX(rng -> new CNG(rng, NoiseType.HEX_SIMPLEX, 1D, 4).scale(1)), - - @Desc("Fractal hexagonal gradient noise with randomized local hex sizes and blended random/simplex heatmaps.") - FRACTAL_HEX_RANDOM_SIZE(rng -> new CNG(rng, NoiseType.HEX_RANDOM_SIZE, 1D, 4).scale(1)), - - @Desc("Fractal Sierpinski triangle mask blended with simplex heat.") - FRACTAL_SIERPINSKI_TRIANGLE(rng -> new CNG(rng, NoiseType.SIERPINSKI_TRIANGLE, 1D, 4).scale(1)), - - @Desc("Rigid Multi Fractal Simplex Noise. Single octave.") - FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 1)), - - @Desc("Billow Fractal Simplex Noise. 2 octaves.") - BIOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 2)), - - @Desc("FBM Fractal Simplex Noise. 2 octaves.") - BIOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 2)), - - @Desc("Rigid Multi Fractal Simplex Noise. 2 octaves.") - BIOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 2)), - - @Desc("Rigid Multi Fractal Simplex Noise. 3 octaves.") - TRIOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 3)), - - @Desc("Billow Fractal Simplex Noise. 3 octaves.") - TRIOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 3)), - - @Desc("FBM Fractal Simplex Noise. 3 octaves.") - TRIOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 3)), - - @Desc("Rigid Multi Fractal Simplex Noise. 4 octaves.") - QUADOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 4)), - - @Desc("Billow Fractal Simplex Noise. 4 octaves.") - QUADOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 4)), - - @Desc("FBM Fractal Simplex Noise. 4 octaves.") - QUADOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 4)), - - @Desc("Rigid Multi Fractal Simplex Noise. 5 octaves.") - QUINTOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 5)), - - @Desc("Billow Fractal Simplex Noise. 5 octaves.") - QUINTOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 5)), - - @Desc("FBM Fractal Simplex Noise. 5 octaves.") - QUINTOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 5)), - - @Desc("Rigid Multi Fractal Simplex Noise. 6 octaves.") - SEXOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 6)), - - @Desc("Billow Fractal Simplex Noise. 6 octaves.") - SEXOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 6)), - - @Desc("FBM Fractal Simplex Noise. 6 octaves.") - SEXOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 6)), - - @Desc("Rigid Multi Fractal Simplex Noise. 7 octaves.") - SEPTOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 7)), - - @Desc("Billow Fractal Simplex Noise. 7 octaves.") - SEPTOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 7)), - - @Desc("FBM Fractal Simplex Noise. 7 octaves.") - SEPTOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 7)), - - @Desc("Rigid Multi Fractal Simplex Noise. 8 octaves.") - OCTOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 8)), - - @Desc("Billow Fractal Simplex Noise. 8 octaves.") - OCTOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 8)), - - @Desc("FBM Fractal Simplex Noise. 8 octaves.") - OCTOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 8)), - - @Desc("Rigid Multi Fractal Simplex Noise. 9 octaves.") - NONOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 9)), - - @Desc("Billow Fractal Simplex Noise. 9 octaves.") - NONOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 9)), - - @Desc("FBM Fractal Simplex Noise. 9 octaves.") - NONOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 9)), - - @Desc("Rigid Multi Fractal Simplex Noise. 10 octaves.") - VIGOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 10)), - - @Desc("Billow Fractal Simplex Noise. 10 octaves.") - VIGOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 10)), - - @Desc("FBM Fractal Simplex Noise. 10 octaves.") - VIGOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 10)), - - @Desc("Basic, Smooth & Fast Simplex noise. Uses 2 octaves") - BIOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 2).scale(1D / 2D)), - - @Desc("Basic, Smooth & Fast Simplex noise. Uses 3 octaves") - TRIOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 3).scale(1D / 3D)), - - @Desc("Basic, Smooth & Fast Simplex noise. Uses 4 octaves") - QUADOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 4).scale(1D / 4D)), - - @Desc("Basic, Smooth & Fast Simplex noise. Uses 5 octaves") - QUINTOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 5).scale(1D / 5D)), - - @Desc("Basic, Smooth & Fast Simplex noise. Uses 6 octaves") - SEXOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 6).scale(1D / 6D)), - - @Desc("Basic, Smooth & Fast Simplex noise. Uses 7 octaves") - SEPTOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 7).scale(1D / 12D)), - - @Desc("Basic, Smooth & Fast Simplex noise. Uses 8 octaves") - OCTOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 8).scale(1D / 25D)), - - @Desc("Basic, Smooth & Fast Simplex noise. Uses 9 octaves") - NONOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 9).scale(1D / 50D)), - - @Desc("Basic, Smooth & Fast Simplex noise. Uses 10 octaves") - VIGOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 10).scale(1D / 100D)), - - @Desc("Glob noise is like cellular, but with globs...") - GLOB(rng -> new CNG(rng, NoiseType.GLOB, 1D, 1)), - - @Desc("Glob noise is like cellular, but with globs...") - GLOB_IRIS(rng -> CNG.signature(rng, NoiseType.GLOB)), - - @Desc("Glob noise is like cellular, but with globs...") - GLOB_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.GLOB)), - - @Desc("Glob noise is like cellular, but with globs...") - GLOB_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.GLOB)), - - @Desc("Glob noise is like cellular, but with globs...") - GLOB_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.GLOB)), - - @Desc("Cubic Noise") - CUBIC(rng -> new CNG(rng, NoiseType.CUBIC, 1D, 1).scale(256)), - - @Desc("Fractal Cubic Noise") - FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 1).scale(2)), - - @Desc("Fractal Cubic Noise With Iris Swirls") - FRACTAL_CUBIC_IRIS(rng -> CNG.signature(rng, NoiseType.FRACTAL_CUBIC).scale(2)), - - @Desc("Fractal Cubic Noise With Iris Swirls") - FRACTAL_CUBIC_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.FRACTAL_CUBIC).scale(2)), - - @Desc("Fractal Cubic Noise With Iris Swirls") - FRACTAL_CUBIC_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.FRACTAL_CUBIC).scale(2)), - - @Desc("Fractal Cubic Noise With Iris Swirls") - FRACTAL_CUBIC_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.FRACTAL_CUBIC).scale(2)), - - @Desc("Fractal Cubic Noise, 2 Octaves") - BIOCTAVE_FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 2).scale(2)), - - @Desc("Fractal Cubic Noise, 3 Octaves") - TRIOCTAVE_FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 3).scale(1.5)), - - @Desc("Fractal Cubic Noise, 4 Octaves") - QUADOCTAVE_FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 4).scale(1)), - - @Desc("Cubic Noise") - CUBIC_IRIS(rng -> CNG.signature(rng, NoiseType.CUBIC).scale(256)), - - @Desc("Cubic Noise") - CUBIC_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.CUBIC).scale(256)), - - @Desc("Cubic Noise") - CUBIC_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.CUBIC).scale(256)), - - @Desc("Cubic Noise") - CUBIC_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.CUBIC).scale(256)), - - @Desc("Hexagonal cell noise distorted using Iris styled wispy noise.") - HEXAGON_IRIS(rng -> CNG.signature(rng, NoiseType.HEXAGON).scale(1)), - - @Desc("Hexagonal cell noise distorted using Iris styled wispy noise.") - HEXAGON_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.HEXAGON).scale(1)), - - @Desc("Hexagonal cell noise distorted using Iris styled wispy noise.") - HEXAGON_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.HEXAGON).scale(1)), - - @Desc("Hexagonal cell noise distorted using Iris styled wispy noise.") - HEXAGON_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.HEXAGON).scale(1)), - - @Desc("Hex James substitution pattern distorted using Iris styled wispy noise.") - HEX_JAMES_IRIS(rng -> CNG.signature(rng, NoiseType.HEX_JAMES).scale(1)), - - @Desc("Hex James substitution pattern distorted using Iris styled wispy noise.") - HEX_JAMES_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.HEX_JAMES).scale(1)), - - @Desc("Hex James substitution pattern distorted using Iris styled wispy noise.") - HEX_JAMES_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.HEX_JAMES).scale(1)), - - @Desc("Hex James substitution pattern distorted using Iris styled wispy noise.") - HEX_JAMES_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.HEX_JAMES).scale(1)), - - @Desc("Interlocked solid hex-cell simplex heatmap distorted using Iris styled wispy noise.") - HEX_SIMPLEX_IRIS(rng -> CNG.signature(rng, NoiseType.HEX_SIMPLEX).scale(1)), - - @Desc("Interlocked solid hex-cell simplex heatmap distorted using Iris styled wispy noise.") - HEX_SIMPLEX_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.HEX_SIMPLEX).scale(1)), - - @Desc("Interlocked solid hex-cell simplex heatmap distorted using Iris styled wispy noise.") - HEX_SIMPLEX_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.HEX_SIMPLEX).scale(1)), - - @Desc("Interlocked solid hex-cell simplex heatmap distorted using Iris styled wispy noise.") - HEX_SIMPLEX_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.HEX_SIMPLEX).scale(1)), - - @Desc("Hexagonal random-size gradient noise and distorted using Iris styled wispy noise.") - HEX_RANDOM_SIZE_IRIS(rng -> CNG.signature(rng, NoiseType.HEX_RANDOM_SIZE).scale(1)), - - @Desc("Hexagonal random-size gradient noise and distorted using Iris styled wispy noise.") - HEX_RANDOM_SIZE_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.HEX_RANDOM_SIZE).scale(1)), - - @Desc("Hexagonal random-size gradient noise and distorted using Iris styled wispy noise.") - HEX_RANDOM_SIZE_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.HEX_RANDOM_SIZE).scale(1)), - - @Desc("Hexagonal random-size gradient noise and distorted using Iris styled wispy noise.") - HEX_RANDOM_SIZE_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.HEX_RANDOM_SIZE).scale(1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders. Cells are distorted using Iris styled wispy noise.") - CELLULAR_IRIS(rng -> CNG.signature(rng, NoiseType.CELLULAR)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders. Cells are distorted using Iris styled wispy noise.") - CELLULAR_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.CELLULAR)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders. Cells are distorted using Iris styled wispy noise.") - CELLULAR_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.CELLULAR)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders. Cells are distorted using Iris styled wispy noise.") - CELLULAR_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.CELLULAR)), - - @Desc("Inverse of vascular, height gets to 1.0 as it approaches the center of a cell") - CELLULAR_HEIGHT(rng -> new CNG(rng, NoiseType.CELLULAR_HEIGHT, 1D, 1)), - - @Desc("Inverse of vascular, height gets to 1.0 as it approaches the center of a cell, using the iris style.") - CELLULAR_HEIGHT_IRIS(rng -> CNG.signature(rng, NoiseType.CELLULAR_HEIGHT)), - - @Desc("Inverse of vascular, height gets to 1.0 as it approaches the center of a cell, using the iris style.") - CELLULAR_HEIGHT_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.CELLULAR_HEIGHT)), - - @Desc("Inverse of vascular, height gets to 1.0 as it approaches the center of a cell, using the iris style.") - CELLULAR_HEIGHT_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.CELLULAR_HEIGHT)), - - @Desc("Inverse of vascular, height gets to 1.0 as it approaches the center of a cell, using the iris style.") - CELLULAR_HEIGHT_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.CELLULAR_HEIGHT)), - - @Desc("Vascular noise gets higher as the position nears a cell border. Cells are distorted using Iris styled wispy noise.") - VASCULAR_IRIS(rng -> CNG.signature(rng, NoiseType.VASCULAR)), - - @Desc("Vascular noise gets higher as the position nears a cell border. Cells are distorted using Iris styled wispy noise.") - VASCULAR_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.VASCULAR)), - - @Desc("Vascular noise gets higher as the position nears a cell border. Cells are distorted using Iris styled wispy noise.") - VASCULAR_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.VASCULAR)), - - @Desc("Vascular noise gets higher as the position nears a cell border. Cells are distorted using Iris styled wispy noise.") - VASCULAR_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.VASCULAR)), - ; - - private final CNGFactory f; - - NoiseStyle(CNGFactory f) { - this.f = f; - } - - public ProceduralStream stream(RNG seed) { - return create(seed).stream(); - } - - public ProceduralStream stream(long seed) { - return create(new RNG(seed)).stream(); - } - - public CNG create(RNG seed) { - CNG cng = f.create(seed).bake(); - cng.setLeakStyle(this); - return cng; - } - - public IrisGeneratorStyle style() { - return new IrisGeneratorStyle(this); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/noise/expression/IrisExpression.java b/src/main/java/art/arcane/iris/engine/object/noise/expression/IrisExpression.java deleted file mode 100644 index 77c6a3b3f..000000000 --- a/src/main/java/art/arcane/iris/engine/object/noise/expression/IrisExpression.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.noise.expression; - -import art.arcane.iris.spi.IrisLogging; -import com.dfsek.paralithic.Expression; -import com.dfsek.paralithic.eval.parser.Parser; -import com.dfsek.paralithic.eval.parser.Scope; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.object.noise.expression.IrisExpressionFunction.FunctionContext; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.util.project.stream.ProceduralStream; -import art.arcane.iris.util.project.stream.interpolation.Interpolated; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents an Iris Expression") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisExpression extends IrisRegistrant { - @ArrayType(type = IrisExpressionLoad.class, min = 1) - @Desc("Variables to use in this expression") - private KList variables = new KList<>(); - - @ArrayType(type = IrisExpressionFunction.class, min = 1) - @Desc("Functions to use in this expression") - private KList functions = new KList<>(); - - @Required - @Desc("The expression. Inherited variables are x, y and z. Avoid using those variable names.") - private String expression; - - private transient AtomicCache expressionCache = new AtomicCache<>(); - private transient AtomicCache> streamCache = new AtomicCache<>(); - - private Expression expression() { - return expressionCache.aquire(() -> { - Scope scope = new Scope(); // Create variable scope. This scope can hold both constants and invocation variables. - Parser parser = new Parser(); - - try { - for (IrisExpressionLoad i : variables) { - scope.addInvocationVariable(i.getName()); - } - - scope.addInvocationVariable("x"); - scope.addInvocationVariable("y"); - scope.addInvocationVariable("z"); - } catch (Throwable e) { - IrisLogging.reportError("Script variable load failed in " + getLoadFile().getPath() + ".", e); - } - - for (IrisExpressionFunction f : functions) { - if (!f.isValid()) continue; - f.setData(getLoader()); - parser.registerFunction(f.getName(), f); - } - - try { - return parser.parse(getExpression(), scope); - } catch (Throwable e) { - IrisLogging.reportError("Script load failed in " + getLoadFile().getPath() + ".", e); - } - - return null; - }); - } - - public ProceduralStream stream(RNG rng) { - return streamCache.aquire(() -> ProceduralStream.of((x, z) -> evaluate(rng, x, z), - (x, y, z) -> evaluate(rng, x, y, z), Interpolated.DOUBLE)); - } - - public double evaluate(RNG rng, double x, double z) { - double[] g = new double[3 + getVariables().size()]; - int m = 0; - for (IrisExpressionLoad i : getVariables()) { - g[m++] = i.getValue(rng, getLoader(), x, z); - } - - g[m++] = x; - g[m++] = z; - g[m] = -1; - - return expression().evaluate(new FunctionContext(rng), g); - } - - public double evaluate(RNG rng, double x, double y, double z) { - double[] g = new double[3 + getVariables().size()]; - int m = 0; - for (IrisExpressionLoad i : getVariables()) { - g[m++] = i.getValue(rng, getLoader(), x, y, z); - } - - g[m++] = x; - g[m++] = y; - g[m] = z; - - return expression().evaluate(new FunctionContext(rng), g); - } - - @Override - public String getFolderName() { - return "expressions"; - } - - @Override - public String getTypeName() { - return "Expression"; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/noise/expression/IrisExpressionFunction.java b/src/main/java/art/arcane/iris/engine/object/noise/expression/IrisExpressionFunction.java deleted file mode 100644 index 296d3b356..000000000 --- a/src/main/java/art/arcane/iris/engine/object/noise/expression/IrisExpressionFunction.java +++ /dev/null @@ -1,110 +0,0 @@ -package art.arcane.iris.engine.object.noise.expression; - -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.runtime.IrisEngineStreamType; -import com.dfsek.paralithic.functions.dynamic.Context; -import com.dfsek.paralithic.functions.dynamic.DynamicFunction; -import com.dfsek.paralithic.node.Statefulness; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.collection.KMap; -import art.arcane.volmlib.util.math.RNG; -import lombok.AccessLevel; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.NonNull; -import lombok.Setter; -import lombok.experimental.Accessors; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -@Snippet("expression-function") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a function to use in your expression. Do not set the name to x, y, or z, also don't duplicate names.") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisExpressionFunction implements DynamicFunction { - @Required - @Desc("The function to assign this value to. Do not set the name to x, y, or z") - private String name; - - @Desc("If defined, this variable will use a generator style as it's value") - private IrisGeneratorStyle styleValue = null; - - @Desc("If defined, iris will use an internal stream from the engine as it's value") - private IrisEngineStreamType engineStreamValue = null; - - @MinNumber(2) - @Desc("Number of arguments for the function") - private int args = 2; - - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private transient final KMap cache = new KMap<>(); - private transient IrisData data; - - public boolean isValid() { - return styleValue != null || engineStreamValue != null; - } - - @Override - public int getArgNumber() { - if (engineStreamValue != null) return 2; - return Math.max(args, 2); - } - - @NotNull - @Override - public Statefulness statefulness() { - return Statefulness.STATEFUL; - } - - @Override - public double eval(double... doubles) { - return 0; - } - - @Override - public double eval(@Nullable Context raw, double... args) { - return cache.computeIfAbsent((FunctionContext) raw, context -> { - assert context != null; - if (engineStreamValue != null) { - var stream = engineStreamValue.get(data.getEngine()); - return d -> stream.get(d[0], d[1]); - } - - if (styleValue != null) { - return styleValue.createNoCache(context.rng, data)::noise; - } - - return d -> Double.NaN; - }).eval(args); - } - - public record FunctionContext(@NonNull RNG rng) implements Context { - @Override - public boolean equals(Object o) { - if (o == null || getClass() != o.getClass()) return false; - FunctionContext that = (FunctionContext) o; - return rng.getSeed() == that.rng.getSeed(); - } - - @Override - public int hashCode() { - return Long.hashCode(rng.getSeed()); - } - } - - @FunctionalInterface - private interface Provider { - double eval(double... args); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/noise/expression/IrisExpressionLoad.java b/src/main/java/art/arcane/iris/engine/object/noise/expression/IrisExpressionLoad.java deleted file mode 100644 index fa69066d8..000000000 --- a/src/main/java/art/arcane/iris/engine/object/noise/expression/IrisExpressionLoad.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.noise.expression; - -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.runtime.IrisEngineStreamType; -import art.arcane.iris.engine.object.runtime.IrisEngineValueType; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.volmlib.util.cache.LazyBoundedCache; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.iris.util.project.stream.ProceduralStream; -import lombok.AccessLevel; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.experimental.Accessors; - -import java.util.Collections; -import java.util.IdentityHashMap; -import java.util.Iterator; -import java.util.Map; - -@Snippet("expression-load") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a variable to use in your expression. Do not set the name to x, y, or z, also don't duplicate names.") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisExpressionLoad { - private static final int STYLE_CACHE_SIZE = 8; - @Required - @Desc("The variable to assign this value to. Do not set the name to x, y, or z") - private String name = ""; - - @Desc("If the style value is not defined, this value will be used") - private double staticValue = -1; - - @Desc("If defined, this variable will use a generator style as it's value") - private IrisGeneratorStyle styleValue = null; - - @Desc("If defined, iris will use an internal stream from the engine as it's value") - private IrisEngineStreamType engineStreamValue = null; - - @Desc("If defined, iris will use an internal value from the engine as it's value") - private IrisEngineValueType engineValue = null; - - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private transient final Map engineCaches = - Collections.synchronizedMap(new IdentityHashMap<>()); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private transient final LazyBoundedCache standaloneStyleCache = - new LazyBoundedCache<>(STYLE_CACHE_SIZE); - - public double getValue(RNG rng, IrisData data, double x, double z) { - if (engineValue != null) { - Engine engine = requireEngine(data); - return cacheFor(engine).value.aquire(() -> engineValue.get(engine)); - } - - if (engineStreamValue != null) { - Engine engine = requireEngine(data); - return cacheFor(engine).stream.aquire(() -> engineStreamValue.get(engine)).get(x, z); - } - - if (styleValue != null) { - return style(data, rng).noise(x, z); - } - - return staticValue; - } - - public double getValue(RNG rng, IrisData data, double x, double y, double z) { - if (engineValue != null) { - Engine engine = requireEngine(data); - return cacheFor(engine).value.aquire(() -> engineValue.get(engine)); - } - - if (engineStreamValue != null) { - Engine engine = requireEngine(data); - return cacheFor(engine).stream.aquire(() -> engineStreamValue.get(engine)).get(x, z); - } - - if (styleValue != null) { - return style(data, rng).noise(x, y, z); - } - - return staticValue; - } - - private Engine requireEngine(IrisData data) { - Engine engine = data.getEngine(); - if (engine == null) { - throw new IllegalStateException("Expression variable '" + name + "' requires an active Iris engine."); - } - return engine; - } - - private EngineCache cacheFor(Engine engine) { - synchronized (engineCaches) { - Iterator> iterator = engineCaches.entrySet().iterator(); - while (iterator.hasNext()) { - if (iterator.next().getKey().isClosed()) { - iterator.remove(); - } - } - EngineCache cache = engineCaches.get(engine); - if (cache != null) { - return cache; - } - EngineCache created = new EngineCache(); - engineCaches.put(engine, created); - return created; - } - } - - private CNG style(IrisData data, RNG rng) { - Engine engine = data.getEngine(); - long seed = rng.getSeed(); - if (engine != null) { - return cacheFor(engine).styles.computeIfAbsent(seed, - ignored -> styleValue.createNoCache(new RNG(seed), data)); - } - StandaloneStyleKey key = new StandaloneStyleKey(data, seed); - return standaloneStyleCache.computeIfAbsent(key, - ignored -> styleValue.createNoCache(new RNG(seed), data)); - } - - private static final class EngineCache { - private final AtomicCache> stream = new AtomicCache<>(); - private final AtomicCache value = new AtomicCache<>(); - private final LazyBoundedCache styles = new LazyBoundedCache<>(STYLE_CACHE_SIZE); - } - - private static final class StandaloneStyleKey { - private final IrisData data; - private final long seed; - - private StandaloneStyleKey(IrisData data, long seed) { - this.data = data; - this.seed = seed; - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof StandaloneStyleKey key)) { - return false; - } - return data == key.data && seed == key.seed; - } - - @Override - public int hashCode() { - return 31 * System.identityHashCode(data) + Long.hashCode(seed); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/DecayControlPlacer.java b/src/main/java/art/arcane/iris/engine/object/placement/DecayControlPlacer.java deleted file mode 100644 index 5a6eb97ec..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/DecayControlPlacer.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.spi.PlatformBlockState; -import org.jetbrains.annotations.Nullable; - -public class DecayControlPlacer implements IObjectPlacer { - private final IObjectPlacer delegate; - - public DecayControlPlacer(IObjectPlacer delegate) { - this.delegate = delegate; - } - - @Override - public int getHighest(int x, int z, IrisData data) { - return delegate.getHighest(x, z, data); - } - - @Override - public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) { - return delegate.getHighest(x, z, data, ignoreFluid); - } - - @Override - public void set(int x, int y, int z, PlatformBlockState d) { - delegate.set(x, y, z, d); - } - - @Override - public PlatformBlockState get(int x, int y, int z) { - return delegate.get(x, y, z); - } - - @Override - public boolean isPreventingDecay() { - return false; - } - - @Override - public boolean isCarved(int x, int y, int z) { - return delegate.isCarved(x, y, z); - } - - @Override - public boolean isSurfaceSolid(int x, int y, int z) { - return delegate.isSurfaceSolid(x, y, z); - } - - @Override - public boolean isSolid(int x, int y, int z) { - return delegate.isSolid(x, y, z); - } - - @Override - public boolean isUnderwater(int x, int z) { - return delegate.isUnderwater(x, z); - } - - @Override - public int getFluidHeight() { - return delegate.getFluidHeight(); - } - - @Override - public boolean isDebugSmartBore() { - return delegate.isDebugSmartBore(); - } - - @Override - public void setTile(int xx, int yy, int zz, TileData tile) { - delegate.setTile(xx, yy, zz, tile); - } - - @Override - public void setData(int xx, int yy, int zz, T data) { - delegate.setData(xx, yy, zz, data); - } - - @Override - public @Nullable T getData(int xx, int yy, int zz, Class t) { - return delegate.getData(xx, yy, zz, t); - } - - @Override - public Engine getEngine() { - return delegate.getEngine(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/FloatingObjectFootprint.java b/src/main/java/art/arcane/iris/engine/object/placement/FloatingObjectFootprint.java deleted file mode 100644 index 6c9b80444..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/FloatingObjectFootprint.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.object.prefab.IrisObject; -import java.util.HashMap; -import java.util.Map; - -public class FloatingObjectFootprint { - private final int lowestSolidKeyY; - private final int highestSolidKeyY; - private final int centerX; - private final int centerY; - private final int centerZ; - private final int tallestKx; - private final int tallestKz; - private final int tallestKxBottom; - private final int tallestKzBottom; - private final long[] footprintXZ; - - private FloatingObjectFootprint(int lowestSolidKeyY, int highestSolidKeyY, int centerX, int centerY, int centerZ, int tallestKx, int tallestKz, int tallestKxBottom, int tallestKzBottom, long[] footprintXZ) { - this.lowestSolidKeyY = lowestSolidKeyY; - this.highestSolidKeyY = highestSolidKeyY; - this.centerX = centerX; - this.centerY = centerY; - this.centerZ = centerZ; - this.tallestKx = tallestKx; - this.tallestKz = tallestKz; - this.tallestKxBottom = tallestKxBottom; - this.tallestKzBottom = tallestKzBottom; - this.footprintXZ = footprintXZ; - } - - /** - * Memoized per object instance, never in a global map: loadKey + declared dimensions is - * not unique across packs or across hotloads (a block edit keeps the header W/H/D), so a - * shared key space served stale or foreign footprints. A reload builds a new IrisObject, - * which drops the memo for free. - */ - public static FloatingObjectFootprint compute(IrisObject obj) { - return obj.floatingFootprint.aquire(() -> doCompute(obj)); - } - - private static FloatingObjectFootprint doCompute(IrisObject obj) { - int cx = obj.getCenter().getBlockX(); - int cy = obj.getCenter().getBlockY(); - int cz = obj.getCenter().getBlockZ(); - Map columnStats = new HashMap<>(); - - int[] globalHighestY = {Integer.MIN_VALUE}; - int[] globalHighestKx = {0}; - int[] globalHighestKz = {0}; - - obj.getBlocks().forEach((key, bd) -> { - if (!bd.isSolid()) { - return; - } - int kx = key.getBlockX(); - int ky = key.getBlockY(); - int kz = key.getBlockZ(); - long packed = ((long) kx << 32) | (kz & 0xFFFFFFFFL); - int[] stats = columnStats.get(packed); - if (stats == null) { - stats = new int[]{ky, 1}; - columnStats.put(packed, stats); - } else { - if (ky < stats[0]) { - stats[0] = ky; - } - stats[1]++; - } - if (ky > globalHighestY[0]) { - globalHighestY[0] = ky; - globalHighestKx[0] = kx; - globalHighestKz[0] = kz; - } - }); - - long[] footprintArray = new long[columnStats.size()]; - int idx = 0; - for (Long packed : columnStats.keySet()) { - footprintArray[idx++] = packed; - } - - long tallestPacked = resolveTallestColumn(columnStats); - int lowestSolidKeyY = columnStats.isEmpty() ? cy : columnStats.get(tallestPacked)[0]; - int highestSolidKeyY = columnStats.isEmpty() ? cy : globalHighestY[0]; - int tallestKx = columnStats.isEmpty() ? 0 : (int) (tallestPacked >> 32); - int tallestKz = columnStats.isEmpty() ? 0 : (int) (tallestPacked & 0xFFFFFFFFL); - int tallestKxBottom = columnStats.isEmpty() ? 0 : globalHighestKx[0]; - int tallestKzBottom = columnStats.isEmpty() ? 0 : globalHighestKz[0]; - return new FloatingObjectFootprint(lowestSolidKeyY, highestSolidKeyY, cx, cy, cz, tallestKx, tallestKz, tallestKxBottom, tallestKzBottom, footprintArray); - } - - private static long resolveTallestColumn(Map columnStats) { - long bestPacked = 0L; - int tallestCount = 0; - int tallestLow = Integer.MAX_VALUE; - for (Map.Entry e : columnStats.entrySet()) { - int[] stats = e.getValue(); - int count = stats[1]; - int low = stats[0]; - if (count > tallestCount || (count == tallestCount && low < tallestLow)) { - tallestCount = count; - tallestLow = low; - bestPacked = e.getKey(); - } - } - return bestPacked; - } - - public int lowestSolidRelCenterY() { - return lowestSolidKeyY - centerY; - } - - public int getLowestSolidKeyY() { - return lowestSolidKeyY; - } - - public int getCenterX() { - return centerX; - } - - public int getCenterY() { - return centerY; - } - - public int getCenterZ() { - return centerZ; - } - - public int getTallestKx() { - return tallestKx; - } - - public int getTallestKz() { - return tallestKz; - } - - public int getHighestSolidKeyY() { - return highestSolidKeyY; - } - - public int getTallestKxBottom() { - return tallestKxBottom; - } - - public int getTallestKzBottom() { - return tallestKzBottom; - } - - public long[] footprintXZ() { - return footprintXZ; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IObjectPlacer.java b/src/main/java/art/arcane/iris/engine/object/placement/IObjectPlacer.java deleted file mode 100644 index 5ba258d83..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/IObjectPlacer.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.spi.PlatformBlockState; -import org.jetbrains.annotations.Nullable; - -public interface IObjectPlacer { - int getHighest(int x, int z, IrisData data); - - int getHighest(int x, int z, IrisData data, boolean ignoreFluid); - - void set(int x, int y, int z, PlatformBlockState d); - - PlatformBlockState get(int x, int y, int z); - - boolean isPreventingDecay(); - - boolean isCarved(int x, int y, int z); - - /** - * Whether the block at this position is real, solid ground. Only live-world placers can answer this; - * at mantle time terrain has not been written yet, so the height stream is the authority. - */ - default boolean isSurfaceSolid(int x, int y, int z) { - return true; - } - - boolean isSolid(int x, int y, int z); - - boolean isUnderwater(int x, int z); - - int getFluidHeight(); - - boolean isDebugSmartBore(); - - void setTile(int xx, int yy, int zz, TileData tile); - - void setData(int xx, int yy, int zz, T data); - - @Nullable T getData(int xx, int yy, int zz, Class t); - - Engine getEngine(); -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IPostBlockAccess.java b/src/main/java/art/arcane/iris/engine/object/placement/IPostBlockAccess.java deleted file mode 100644 index 2993767c5..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/IPostBlockAccess.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.object.terrain.carving.CaveResult; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.collection.KList; -import org.bukkit.generator.ChunkGenerator.ChunkData; - -public interface IPostBlockAccess { - PlatformBlockState getPostBlock(int x, int y, int z, int currentPostX, int currentPostZ, ChunkData currentData); - - void setPostBlock(int x, int y, int z, PlatformBlockState d, int currentPostX, int currentPostZ, ChunkData currentData); - - int highestTerrainOrFluidBlock(int x, int z); - - int highestTerrainBlock(int x, int z); - - void updateHeight(int x, int z, int h); - - KList caveFloors(int x, int z); -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java deleted file mode 100644 index c21ff201d..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java +++ /dev/null @@ -1,325 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.objects.TreeOverride; -import art.arcane.iris.builtin.carve.CaveAnchorMode; -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.builtin.blocks.ObjectReplace; -import art.arcane.iris.builtin.stilt.StiltSettings; -import art.arcane.iris.builtin.prepare.SlopeClip; -import art.arcane.iris.builtin.vacuum.VacuumSettings; -import art.arcane.iris.builtin.validate.ObjectLimit; -import art.arcane.iris.core.modules.ModuleSettings; -import art.arcane.iris.builtin.loot.ObjectLoot; -import art.arcane.iris.builtin.loot.ObjectVanillaLoot; -import art.arcane.iris.builtin.spawn.PlacementMarker; -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.noise.IrisNoiseGenerator; -import art.arcane.iris.engine.object.noise.IrisStyledRange; -import art.arcane.iris.engine.object.noise.NoiseStyle; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectRotation; -import art.arcane.iris.engine.object.prefab.IrisObjectScale; -import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.volmlib.util.cache.LazyBoundedCache; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.iris.util.common.data.DataProvider; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.util.project.noise.CNG; -import com.google.gson.annotations.SerializedName; -import lombok.AccessLevel; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.experimental.Accessors; -import org.bukkit.Bukkit; -import org.jetbrains.annotations.Nullable; - - -@Snippet("object-placer") -@EqualsAndHashCode() -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents an iris object placer. It places objects.") -@Data -public class IrisObjectPlacement { - private static final int SURFACE_WARP_CACHE_SIZE = 8; - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient LazyBoundedCache surfaceWarpCache = - new LazyBoundedCache<>(SURFACE_WARP_CACHE_SIZE); - @RegistryListResource(IrisObject.class) - @Required - @ArrayType(min = 1, type = String.class) - @Desc("List of objects to place") - private KList place = new KList<>(); - @Desc("Rotate this objects placement") - private IrisObjectRotation rotation = new IrisObjectRotation(); - @Desc("Limit the max height or min height of placement.") - private ObjectLimit clamp = new ObjectLimit(); - @MinNumber(0) - @MaxNumber(1) - @Desc("The maximum layer level of a snow filter overtop of this placement. Set to 0 to disable. Max of 1.") - private double snow = 0; - @Desc("Whether or not this object can be targeted by a dolphin.") - private boolean isDolphinTarget = false; - @Desc("The slope at which this object can be placed. Range from 0 to 10 by default. Calculated from a 3-block radius from the center of the object placement.") - private SlopeClip slopeCondition = new SlopeClip(); - @Desc("Set to true to add the rotation of the direction of the slope of the terrain (wherever the slope is going down) to the y-axis rotation of the object." + - "Rounded to 90 degrees. Adds the *min* rotation of the y axis as well (to still allow you to rotate objects nicely). Discards *max* and *interval* on *yaxis*") - private boolean rotateTowardsSlope = false; - @MinNumber(0) - @MaxNumber(1) - @Desc("The chance for this to place in a chunk. If you need multiple per chunk, set this to 1 and use density.") - private double chance = 1; - @MinNumber(1) - @Desc("If the chance check passes, place this many in a single chunk") - private int density = 1; - @Desc("If the chance check passes, and you specify this, it picks a number in the range based on noise, and 'density' is ignored.") - private IrisStyledRange densityStyle = null; - @Desc("When stilting is enabled, this object will define various properties related to it.") - private StiltSettings stiltSettings; - @Desc("When a VACUUM place mode is used, this defines the deformation radius and falloff.") - private VacuumSettings vacuumSettings; - @MaxNumber(64) - @MinNumber(0) - @Desc("When bore is enabled, expand max-y of the cuboid it removes") - private int boreExtendMaxY = 0; - @ArrayType(min = 1, type = PlacementMarker.class) - @Desc("Add markers to blocks in this object") - private KList markers = new KList<>(); - @MaxNumber(64) - @MinNumber(-1) - @Desc("When bore is enabled, lower min-y of the cuboid it removes") - private int boreExtendMinY = 0; - @Desc("If set to true, objects will place on the terrain height, ignoring the water surface.") - private boolean underwater = false; - @Desc("If set to true, objects will place in carvings (such as underground) or under an overhang.") - private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; - @MinNumber(0) - @MaxNumber(16) - @Desc("Extra buffer, in blocks, around this object's base footprint that must also be solid, un-carved ground. 0 checks only the footprint itself.") - private int surfaceSupportBuffer = 2; - @MinNumber(1) - @MaxNumber(16) - @Desc("Minimum thickness, in blocks, of un-carved ground required under every column of this object's base footprint.") - private int surfaceSupportDepth = 2; - @Desc("Set to false to let this placement sit over carved surface openings such as cave entrances.") - private boolean requireSurfaceSupport = true; - @Desc("When carving placement is enabled, select which carved-space anchor this placement targets.") - private CaveAnchorMode caveAnchorMode = CaveAnchorMode.PROFILE_DEFAULT; - @Desc("If this is defined, this object wont place on the terrain heightmap, but instead on this virtual heightmap") - private IrisNoiseGenerator heightmap; - @Desc("If set to true, Iris will try to fill the insides of 'rooms' and 'pockets' where air should fit based off of raytrace checks. This prevents a village house placing in an area where a tree already exists, and instead replaces the parts of the tree where the interior of the structure is. \n\nThis operation does not affect warmed-up generation speed however it does slow down loading objects.") - private boolean smartBore = false; - @Desc("If set to true, Blocks placed underwater that could be waterlogged are waterlogged.") - private boolean waterloggable = false; - @Desc("If set to true, objects will place on the fluid height level Such as boats.") - private boolean onwater = false; - @Desc("If set to true, this object will only place parts of itself where blocks already exist. Warning: Melding is very performance intensive!") - private boolean meld = false; - @Desc("If set to true, this object will get placed from the bottom of the world up") - private boolean fromBottom; - @Desc("If set to true, this object will place from the ground up instead of height checks when not y locked to the surface. This is not compatable with X and Z axis rotations (it may look off)") - private boolean bottom = false; - @Desc("If set to true, air will be placed before the schematic places.") - private boolean bore = false; - @Desc("Use a generator to warp the field of coordinates. Using simplex for example would make a square placement warp like a flag") - private IrisGeneratorStyle warp = new IrisGeneratorStyle(NoiseStyle.FLAT); - @Desc("The placement mode") - private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; - @ArrayType(min = 1, type = ObjectReplace.class) - @Desc("Find and replace blocks") - private KList edit = new KList<>(); - @Desc("Translate this object's placement") - private IrisObjectTranslate translate = new IrisObjectTranslate(); - @Desc("Scale Objects") - private IrisObjectScale scale = new IrisObjectScale(); - @ArrayType(min = 1, type = ObjectLoot.class) - @Desc("The loot tables to apply to these objects") - private KList loot = new KList<>(); - @ArrayType(min = 1, type = ObjectVanillaLoot.class) - @Desc("The vanilla loot tables to apply to these objects") - private KList vanillaLoot = new KList<>(); - @Desc("Whether the given loot tables override any and all other loot tables available in the dimension, region or biome.") - private boolean overrideGlobalLoot = false; - @Desc("This object / these objects override the following trees when they grow...") - @ArrayType(min = 1, type = TreeOverride.class) - private KList trees = new KList<>(); - @RegistryListResource(IrisObject.class) - @ArrayType(type = String.class) - @Desc("List of objects to this object is allowed to collied with") - private KList allowedCollisions = new KList<>(); - @RegistryListResource(IrisObject.class) - @ArrayType(type = String.class) - @Desc("List of objects to this object is forbidden to collied with") - private KList forbiddenCollisions = new KList<>(); - @Desc("Ignore any placement restrictions for this object") - @SerializedName(value = "forcePlace", alternate = {"force"}) - private boolean forcePlace = false; - /** The pack modules' settings this placement declares, decoded with it. */ - private transient ModuleSettings moduleSettings = ModuleSettings.NONE; - - /** A placement that stamps each object exactly at the position it is given, as a structure piece. */ - public static IrisObjectPlacement stampingStructurePieces() { - return new IrisObjectPlacement().setMode(ObjectPlaceMode.STRUCTURE_PIECE); - } - - public IrisObjectPlacement toPlacement(String... place) { - IrisObjectPlacement p = new IrisObjectPlacement(); - p.setPlace(new KList<>(place)); - p.setMode(mode); - p.setEdit(edit); - p.setTranslate(translate); - p.setScale(scale); - p.setWarp(warp); - p.setBore(bore); - p.setMeld(meld); - p.setWaterloggable(waterloggable); - p.setOnwater(onwater); - p.setFromBottom(fromBottom); - p.setBottom(bottom); - p.setSmartBore(smartBore); - p.setCarvingSupport(carvingSupport); - p.setSurfaceSupportBuffer(surfaceSupportBuffer); - p.setSurfaceSupportDepth(surfaceSupportDepth); - p.setRequireSurfaceSupport(requireSurfaceSupport); - p.setCaveAnchorMode(caveAnchorMode); - p.setUnderwater(underwater); - p.setHeightmap(heightmap); - p.setBoreExtendMaxY(boreExtendMaxY); - p.setBoreExtendMinY(boreExtendMinY); - p.setStiltSettings(stiltSettings); - p.setVacuumSettings(vacuumSettings); - p.setDensity(density); - p.setDensityStyle(densityStyle); - p.setChance(chance); - p.setSnow(snow); - p.setClamp(clamp); - p.setRotation(rotation); - p.setSlopeCondition(slopeCondition); - p.setRotateTowardsSlope(rotateTowardsSlope); - p.setDolphinTarget(isDolphinTarget); - p.setMarkers(markers); - p.setLoot(loot); - p.setVanillaLoot(vanillaLoot); - p.setOverrideGlobalLoot(overrideGlobalLoot); - p.setTrees(trees); - p.setAllowedCollisions(allowedCollisions); - p.setForbiddenCollisions(forbiddenCollisions); - p.setForcePlace(forcePlace); - p.setModuleSettings(moduleSettings); - return p; - } - - public CNG getSurfaceWarp(RNG rng, IrisData data) { - return getSurfaceWarp(rng, data, data.getEngine()); - } - - public CNG getSurfaceWarp(RNG rng, IrisData data, @Nullable Engine engine) { - long seed = engine == null ? rng.getSeed() : engine.getSeedManager().getComponent() + 1024L; - SurfaceWarpCacheKey key = new SurfaceWarpCacheKey(data, engine, seed); - return surfaceWarpCache.computeIfAbsent(key, - ignored -> getWarp().create(new RNG(seed), data, engine)); - } - - public double warp(RNG rng, double x, double y, double z, IrisData data) { - return getSurfaceWarp(rng, data).fitDouble(-(getWarp().getMultiplier() / 2D), (getWarp().getMultiplier() / 2D), x, y, z); - } - - public IrisObject getObject(DataProvider g, RNG random) { - if (place.isEmpty()) { - return null; - } - - return g.getData().getObjectLoader().load(place.get(random.nextInt(place.size()))); - } - - /** Whether a tree placement grows the species the platform calls {@code species} for a sapling area of {@code width} by {@code depth}. */ - public boolean matches(int width, int depth, String species) { - for (TreeOverride tree : getTrees()) { - if (tree.matches(width, depth, species)) { - return true; - } - } - - return false; - } - - public int getDensity() { - if (densityStyle == null) { - return density; - } - return densityStyle.getMid(); - } - - public int getDensity(RNG rng, double x, double z, IrisData data) { - if (densityStyle == null) { - return density; - } - - return (int) Math.round(densityStyle.get(rng, x, z, data)); - } - - private static final class SurfaceWarpCacheKey { - private final IrisData data; - private final Engine engine; - private final long seed; - - private SurfaceWarpCacheKey(IrisData data, Engine engine, long seed) { - this.data = data; - this.engine = engine; - this.seed = seed; - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof SurfaceWarpCacheKey key)) { - return false; - } - return data == key.data && engine == key.engine && seed == key.seed; - } - - @Override - public int hashCode() { - int result = System.identityHashCode(data); - result = 31 * result + System.identityHashCode(engine); - return 31 * result + Long.hashCode(seed); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlacements.java b/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlacements.java deleted file mode 100644 index 9d34d6947..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlacements.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.builtin.objects.ObjectPlacement; -import art.arcane.iris.builtin.objects.ObjectSettings; -import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings; -import art.arcane.iris.builtin.objects.SurfaceSupportBufferSettings; -import art.arcane.iris.builtin.objects.TreeGrowthSettings; -import art.arcane.iris.builtin.objects.UpperObjectsForceSettings; -import art.arcane.iris.builtin.objects.UpperObjectsSettings; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.volmlib.util.collection.KList; - -import java.util.Collections; -import java.util.Map; -import java.util.WeakHashMap; - -/** - * The object placements a region or biome declares, as Iris places them: the module settings of - * {@code iris:objects}, made into Iris's own placements once and kept for as long as the settings live. - */ -public final class ObjectPlacements { - private static final Map PLACEMENTS = Collections.synchronizedMap(new WeakHashMap<>()); - - private ObjectPlacements() { - } - - /** Every placement {@code owner} declares. */ - public static KList all(IrisRegistrant owner) { - return placementsOf(owner).all; - } - - /** The placements of {@code owner} that place on the surface. */ - public static KList surface(IrisRegistrant owner) { - return placementsOf(owner).surface; - } - - /** The placements of {@code owner} that place in carvings. */ - public static KList carving(IrisRegistrant owner) { - return placementsOf(owner).carving; - } - - /** Whether {@code dimension} places its objects in the terrain stacked above it too. */ - public static boolean upperObjects(IrisRegistrant dimension) { - return dimension.getModuleSettings().find(UpperObjectsSettings.class).map(UpperObjectsSettings::enabled).orElse(false); - } - - /** Whether the objects placed in the terrain stacked above ignore placement restrictions. */ - public static boolean upperObjectsForced(IrisRegistrant dimension) { - return dimension.getModuleSettings().find(UpperObjectsForceSettings.class).map(UpperObjectsForceSettings::force).orElse(false); - } - - /** Whether {@code dimension} refuses surface objects over carved openings. */ - public static boolean requiresSurfaceSupport(IrisRegistrant dimension) { - return dimension.getModuleSettings().find(RequireSurfaceSupportSettings.class).map(RequireSurfaceSupportSettings::require) - .orElse(NO_SURFACE_SUPPORT_REQUIREMENT.require()); - } - - /** The least surface-support buffer {@code dimension} gives its surface objects. */ - public static int surfaceSupportBuffer(IrisRegistrant dimension) { - return dimension.getModuleSettings().find(SurfaceSupportBufferSettings.class).map(SurfaceSupportBufferSettings::buffer) - .orElse(NO_SURFACE_SUPPORT_BUFFER.buffer()); - } - - /** The tree growth settings of {@code dimension}. */ - public static TreeGrowthSettings treeGrowth(IrisRegistrant dimension) { - return dimension.getModuleSettings().find(TreeGrowthSettings.class).orElse(NO_TREE_GROWTH); - } - - /** Iris's placement for the settings {@code placement}, read from the JSON it was written as. */ - public static IrisObjectPlacement host(ObjectPlacement placement, IrisData data) { - Object kept = placement.hostForm(); - if (kept instanceof IrisObjectPlacement hostPlacement) { - return hostPlacement; - } - IrisObjectPlacement made = data.getGson().fromJson(placement.json(), IrisObjectPlacement.class); - placement.hostForm(made); - return made; - } - - private static final RequireSurfaceSupportSettings NO_SURFACE_SUPPORT_REQUIREMENT = new RequireSurfaceSupportSettings(); - private static final SurfaceSupportBufferSettings NO_SURFACE_SUPPORT_BUFFER = new SurfaceSupportBufferSettings(); - private static final TreeGrowthSettings NO_TREE_GROWTH = new TreeGrowthSettings(); - private static final ObjectSettings NO_OBJECTS = new ObjectSettings(); - - private static Placements placementsOf(IrisRegistrant owner) { - ObjectSettings settings = owner.getModuleSettings().find(ObjectSettings.class).orElse(NO_OBJECTS); - Placements found = PLACEMENTS.get(settings); - if (found != null) { - return found; - } - return PLACEMENTS.computeIfAbsent(settings, declared -> new Placements(declared, owner.getLoader())); - } - - private record Placements(KList all, KList surface, KList carving) { - Placements(ObjectSettings settings, IrisData data) { - this(new KList<>(), new KList<>(), new KList<>()); - for (ObjectPlacement declared : settings.objects()) { - IrisObjectPlacement placement = host(declared, data); - all.add(placement); - if (placement.getCarvingSupport().supportsSurface()) { - surface.add(placement); - } - if (placement.getCarvingSupport().supportsCarving()) { - carving.add(placement); - } - } - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java deleted file mode 100644 index 3afc0912a..000000000 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java +++ /dev/null @@ -1,409 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.prefab; - -import art.arcane.iris.builtin.objects.PlaceableObject; -import art.arcane.iris.engine.object.placement.FloatingObjectFootprint; -import art.arcane.iris.engine.object.placement.IObjectPlacer; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.terrain.carving.CarveResult; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.ModuleObjectPlacement; -import art.arcane.iris.core.modules.ObjectGeometry; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.platform.bukkit.BukkitBlockState; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.data.VectorMap; -import art.arcane.iris.util.common.math.AxisAlignedBB; -import art.arcane.volmlib.util.math.IrisBlockVector; -import art.arcane.volmlib.util.math.IrisVector; -import art.arcane.volmlib.util.math.Vector3i; -import art.arcane.iris.util.common.plugin.VolmitSender; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.BlockPosition; -import art.arcane.volmlib.util.math.RNG; -import com.volmit.object.GeneratedObject; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import lombok.experimental.Accessors; -import org.bukkit.Location; -import org.bukkit.block.Block; -import org.bukkit.block.data.BlockData; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.function.BiConsumer; - -/** - * A voxel volume loaded from a .iob file. Instances are loader cached and shared across generation threads, so all - * volume access goes through the read/write lock pair below. - *

- * The heavy behaviour lives in package-private collaborators that read this state directly: - * {@link IrisObjectIO} (binary persistence), {@link IrisObjectShaping} (boring, shrinkwrap, block classification), - * {@link IrisObjectTransforms} (rotation, scaling, interpolated upscaling) and {@link ModuleObjectPlacement} - * (world placement). - */ -@Accessors(chain = true) -@EqualsAndHashCode(callSuper = false) -public class IrisObject extends IrisRegistrant implements PlaceableObject { - protected static final IrisVector HALF = new IrisVector(0.5, 0.5, 0.5); - public static final class States { - public static final PlatformBlockState AIR = B.getState("CAVE_AIR"); - public static final PlatformBlockState STONE = B.getState("STONE"); - public static final PlatformBlockState VAIR = B.getState("VOID_AIR"); - public static final PlatformBlockState VAIR_DEBUG = B.getState("COBWEB"); - public static final PlatformBlockState[] SNOW_LAYERS = new PlatformBlockState[]{B.getState("minecraft:snow[layers=1]"), B.getState("minecraft:snow[layers=2]"), B.getState("minecraft:snow[layers=3]"), B.getState("minecraft:snow[layers=4]"), B.getState("minecraft:snow[layers=5]"), B.getState("minecraft:snow[layers=6]"), B.getState("minecraft:snow[layers=7]"), B.getState("minecraft:snow[layers=8]")}; - } - public transient final Lock readLock; - protected transient final Lock writeLock; - @Getter - @Setter - protected transient volatile boolean smartBored = false; - @Setter - protected transient AtomicCache aabb = new AtomicCache<>(); - transient final AtomicCache> surfaceSupportOffsets = new AtomicCache<>(); - public transient final AtomicCache floatingFootprint = new AtomicCache<>(); - private transient final AtomicCache geometry = new AtomicCache<>(); - @Getter - public VectorMap blocks; - @Getter - public VectorMap states; - @Getter - @Setter - public int w; - @Getter - @Setter - public int d; - @Getter - @Setter - public int h; - @Getter - @Setter - transient Vector3i center; - @Getter - transient Vector3i shrinkOffset; - - public IrisObject(int w, int h, int d) { - blocks = new VectorMap<>(); - states = new VectorMap<>(); - this.w = w; - this.h = h; - this.d = d; - center = new Vector3i(w / 2, h / 2, d / 2); - shrinkOffset = new Vector3i(0, 0, 0); - var lock = new ReentrantReadWriteLock(); - readLock = lock.readLock(); - writeLock = lock.writeLock(); - } - - public IrisObject() { - this(0, 0, 0); - } - - public static AxisAlignedBB getAABBFor(IrisBlockVector size) { - IrisBlockVector center = new IrisBlockVector(size.getX() / 2, size.getY() / 2, size.getZ() / 2); - IrisVector min = new IrisBlockVector(0, 0, 0).subtract(center); - IrisVector max = new IrisBlockVector(size.getX() - 1, size.getY() - 1, size.getZ() - 1).subtract(center); - return new AxisAlignedBB(new IrisPosition(min.getBlockX(), min.getBlockY(), min.getBlockZ()), - new IrisPosition(max.getBlockX(), max.getBlockY(), max.getBlockZ())); - } - - public static IrisBlockVector sampleSize(File file) throws IOException { - return IrisObjectIO.sampleSize(file); - } - - public AxisAlignedBB getAABB() { - return aabb.aquire(() -> getAABBFor(new IrisBlockVector(w, h, d))); - } - - public synchronized IrisObject copy() { - IrisObject o = new IrisObject(w, h, d); - o.setLoadKey(getLoadKey()); - o.setLoader(getLoader()); - o.setLoadFile(getLoadFile()); - o.setCenter(getCenter().clone()); - - blocks.forEach((i, v) -> o.blocks.put(i.clone(), v)); - states.forEach((i, v) -> o.states.put(i.clone(), v.clone())); - - return o; - } - - public void readLegacy(InputStream in) throws IOException { - IrisObjectIO.readLegacy(this, in); - } - - public void read(InputStream in) throws Throwable { - IrisObjectIO.read(this, in); - } - - public void read(File file) throws IOException { - IrisObjectIO.read(this, file); - } - - public void write(OutputStream o) throws IOException { - IrisObjectIO.write(this, o); - } - - public void write(OutputStream o, VolmitSender sender) throws IOException { - IrisObjectIO.write(this, o, sender); - } - - public void write(File file) throws IOException { - IrisObjectIO.write(this, file); - } - - public void write(File file, VolmitSender sender) throws IOException { - IrisObjectIO.write(this, file, sender); - } - - public void shrinkwrap() { - // Instances are loader cached and shared across generation threads; mutating the - // volume without the write lock let a concurrent placement mix pre-shrink anchors - // with post-shrink blocks. Rotation paths call the package-private statics while - // already holding this (reentrant) lock. - writeLock.lock(); - try { - IrisObjectShaping.shrinkwrap(this); - } finally { - writeLock.unlock(); - } - } - - public void clean() { - writeLock.lock(); - try { - IrisObjectShaping.clean(this); - } finally { - writeLock.unlock(); - } - } - - public IrisBlockVector getSigned(int x, int y, int z) { - if (x >= w || y >= h || z >= d) { - throw new RuntimeException(x + " " + y + " " + z + " exceeds limit of " + w + " " + h + " " + d); - } - - return new IrisBlockVector(x - center.getX(), y - center.getY(), z - center.getZ()); - } - - public void setUnsigned(int x, int y, int z, PlatformBlockState block) { - IrisBlockVector v = getSigned(x, y, z); - - if (block == null) { - blocks.remove(v); - states.remove(v); - } else { - blocks.put(v, block); - } - - forgetDerivedShapes(); - } - - public void setUnsignedTile(int x, int y, int z, TileData tile) { - IrisBlockVector v = getSigned(x, y, z); - - if (tile == null) { - states.remove(v); - } else { - states.put(v, tile); - } - - forgetDerivedShapes(); - } - - public void setUnsigned(int x, int y, int z, Block block, boolean legacy) { - IrisBlockVector v = getSigned(x, y, z); - - if (block == null) { - blocks.remove(v); - states.remove(v); - } else { - BlockData data = block.getBlockData(); - blocks.put(v, BukkitBlockState.of(data)); - TileData state = TileData.getTileState(block, legacy); - if (state != null) { - IrisLogging.debug("Saved State " + v); - states.put(v, state); - } - } - - forgetDerivedShapes(); - } - - public int place(int x, int z, IObjectPlacer placer, IrisObjectPlacement config, RNG rng, IrisData rdata) { - return place(x, -1, z, placer, config, rng, rdata); - } - - public int place(int x, int z, IObjectPlacer placer, IrisObjectPlacement config, RNG rng, CarveResult c, IrisData rdata) { - return place(x, -1, z, placer, config, rng, null, c, rdata); - } - - public int place(int x, int yv, int z, IObjectPlacer placer, IrisObjectPlacement config, RNG rng, IrisData rdata) { - return place(x, yv, z, placer, config, rng, null, null, rdata); - } - - public int place(Location loc, IObjectPlacer placer, IrisObjectPlacement config, RNG rng, IrisData rdata) { - return place(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), placer, config, rng, rdata); - } - - /** The height the object was placed at, or -1 when the placement rejected it. */ - public int place(int x, int yv, int z, IObjectPlacer oplacer, IrisObjectPlacement config, RNG rng, BiConsumer listener, CarveResult c, IrisData rdata) { - return ModuleObjectPlacement.place(this, x, yv, z, oplacer, config, rng, listener, c, rdata).heightOrRejected(); - } - - /** This object as IrisApi geometry, read once until its blocks change. */ - public GeneratedObject getGeometry() { - return geometry.aquireOrThrow(() -> ObjectGeometry.of(this)); - } - - /** Drops what is computed from the blocks, after they change. */ - void forgetDerivedShapes() { - surfaceSupportOffsets.reset(); - floatingFootprint.reset(); - geometry.reset(); - } - - public KList getSurfaceSupportOffsets() { - return surfaceSupportOffsets.aquire(() -> { - readLock.lock(); - try { - int lowestY = Integer.MAX_VALUE; - KList offsets = new KList<>(); - for (Map.Entry entry : blocks) { - PlatformBlockState state = entry.getValue(); - if (state == null || !state.isSolid() || state.isFoliage()) { - continue; - } - IrisBlockVector position = entry.getKey(); - int blockY = position.getBlockY(); - if (blockY < lowestY) { - lowestY = blockY; - offsets.clear(); - } - if (blockY == lowestY) { - offsets.add(position.clone()); - } - } - return offsets; - } finally { - readLock.unlock(); - } - }); - } - - public IrisObject rotateCopy(IrisObjectRotation rt) { - return IrisObjectTransforms.rotateCopy(this, rt); - } - - public IrisObject scaled(double scale, IrisObjectPlacementScaleInterpolator interpolation) { - return IrisObjectTransforms.scaled(this, scale, interpolation); - } - - public void place(Location at) { - readLock.lock(); - try { - for (var entry : blocks) { - var i = entry.getKey(); - Block b = at.clone().add(0, getCenter().getY(), 0).add(i.getX(), i.getY(), i.getZ()).getBlock(); - b.setBlockData((BlockData) Objects.requireNonNull(entry.getValue()).nativeHandle(), false); - - if (states.containsKey(i)) { - IrisLogging.info(Objects.requireNonNull(states.get(i)).toString()); - Objects.requireNonNull(states.get(i)).toBukkitTry(b); - } - } - } finally { - readLock.unlock(); - } - } - - public void placeCenterY(Location at) { - readLock.lock(); - try { - for (var entry : blocks) { - var i = entry.getKey(); - Block b = at.clone().add(getCenter().getX(), getCenter().getY(), getCenter().getZ()).add(i.getX(), i.getY(), i.getZ()).getBlock(); - b.setBlockData((BlockData) Objects.requireNonNull(entry.getValue()).nativeHandle(), false); - - if (states.containsKey(i)) { - Objects.requireNonNull(states.get(i)).toBukkitTry(b); - } - } - } finally { - readLock.unlock(); - } - } - - public void unplaceCenterY(Location at) { - readLock.lock(); - try { - for (IrisBlockVector i : blocks.keys()) { - at.clone().add(getCenter().getX(), getCenter().getY(), getCenter().getZ()).add(i.getX(), i.getY(), i.getZ()).getBlock().setBlockData((BlockData) States.AIR.nativeHandle(), false); - } - } finally { - readLock.unlock(); - } - } - - @Override - public String key() { - return getLoadKey(); - } - - @Override - public int width() { - return w; - } - - @Override - public int height() { - return h; - } - - @Override - public int depth() { - return d; - } - - public int volume() { - return blocks.size(); - } - - @Override - public String getFolderName() { - return "objects"; - } - - @Override - public String getTypeName() { - return "Object"; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectIO.java b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectIO.java deleted file mode 100644 index 0e6660bea..000000000 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectIO.java +++ /dev/null @@ -1,394 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.prefab; - -import art.arcane.iris.core.localization.IrisLanguage; -import art.arcane.iris.core.localization.RuntimeUiMessages; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.math.IrisBlockVector; -import art.arcane.volmlib.util.math.Vector3i; -import art.arcane.iris.util.common.plugin.VolmitSender; -import art.arcane.iris.util.common.scheduling.jobs.Job; -import art.arcane.volmlib.util.collection.KList; - -import java.io.BufferedInputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicReference; - -/** - * Binary (.iob) persistence for {@link IrisObject}. The field layout written here is pinned by the on-disk - * format - do not reorder reads or writes. - */ -public final class IrisObjectIO { - private static final String V2_HEADER = "Iris V2 IOB;"; - private static final int MAX_PALETTE_ENTRIES = 32_767; - - private IrisObjectIO() { - } - - /** - * Reads only the V2 palette block-state keys out of an {@code .iob} header. Read-only pack-tooling hook: no - * IrisObject is built and no block state is resolved, so it runs without a bound platform. - *

- * Returns an empty list for a legacy (V1) object, an unreadable file, or a truncated header - a scan must never - * fail pack validation. - */ - public static List readPaletteKeys(File file) { - if (file == null || !file.isFile()) { - return List.of(); - } - try (DataInputStream din = new DataInputStream(new BufferedInputStream(new FileInputStream(file)))) { - din.readInt(); - din.readInt(); - din.readInt(); - if (!V2_HEADER.equals(din.readUTF())) { - return List.of(); - } - int count = din.readShort(); - if (count <= 0 || count > MAX_PALETTE_ENTRIES) { - return List.of(); - } - List palette = new ArrayList<>(count); - for (int i = 0; i < count; i++) { - palette.add(din.readUTF()); - } - return palette; - } catch (Throwable e) { - return List.of(); - } - } - - static IrisBlockVector sampleSize(File file) throws IOException { - try (DataInputStream din = new DataInputStream(new FileInputStream(file))) { - return new IrisBlockVector(din.readInt(), din.readInt(), din.readInt()); - } - } - - static void readLegacy(IrisObject self, InputStream in) throws IOException { - self.forgetDerivedShapes(); - DataInputStream din = new DataInputStream(in); - self.w = din.readInt(); - self.h = din.readInt(); - self.d = din.readInt(); - self.center = new Vector3i(self.w / 2, self.h / 2, self.d / 2); - int s = din.readInt(); - - for (int i = 0; i < s; i++) { - IrisBlockVector pos = new IrisBlockVector(din.readShort(), din.readShort(), din.readShort()); - PlatformBlockState data = B.getState(din.readUTF()); - if (isStructureMarker(data)) { - continue; - } - self.blocks.put(pos, data); - } - - if (din.available() == 0) - return; - - try { - int size = din.readInt(); - - for (int i = 0; i < size; i++) { - self.states.put(new IrisBlockVector(din.readShort(), din.readShort(), din.readShort()), TileData.read(din)); - } - } catch (Throwable e) { - IrisLogging.reportError(e); - } - } - - static void read(IrisObject self, InputStream in) throws Throwable { - self.forgetDerivedShapes(); - DataInputStream din = new DataInputStream(in); - self.w = din.readInt(); - self.h = din.readInt(); - self.d = din.readInt(); - if (!din.readUTF().equals("Iris V2 IOB;")) { - throw new HeaderException(); - } - self.center = new Vector3i(self.w / 2, self.h / 2, self.d / 2); - int s = din.readShort(); - int i; - KList palette = new KList<>(); - - for (i = 0; i < s; i++) { - palette.add(din.readUTF()); - } - - // Resolve the palette once: B.getState per BLOCK was a registry lookup times the - // block count (tens of thousands) instead of times the palette size (hundreds). - PlatformBlockState[] resolved = new PlatformBlockState[palette.size()]; - for (i = 0; i < resolved.length; i++) { - resolved[i] = B.getState(palette.get(i)); - } - - s = din.readInt(); - - for (i = 0; i < s; i++) { - IrisBlockVector pos = new IrisBlockVector(din.readShort(), din.readShort(), din.readShort()); - PlatformBlockState data = resolved[din.readShort()]; - if (isStructureMarker(data)) { - continue; - } - self.blocks.put(pos, data); - } - - s = din.readInt(); - - for (i = 0; i < s; i++) { - self.states.put(new IrisBlockVector(din.readShort(), din.readShort(), din.readShort()), TileData.read(din)); - } - } - - static void read(IrisObject self, File file) throws IOException { - try (var fin = new BufferedInputStream(new FileInputStream(file))) { - read(self, fin); - } catch (Throwable e) { - if (!(e instanceof HeaderException)) - IrisLogging.reportError(e); - // The V2 parse populates blocks/states incrementally; a mid-file failure must not - // leave those entries to be merged with the legacy parse of the same file. - self.blocks.clear(); - self.states.clear(); - try (var fin = new BufferedInputStream(new FileInputStream(file))) { - readLegacy(self, fin); - } - } - } - - private static boolean isStructureMarker(PlatformBlockState data) { - if (data == null) { - return false; - } - String material = IrisObjectShaping.materialKey(data); - return material.equals("minecraft:jigsaw") || material.equals("minecraft:structure_block") || material.equals("minecraft:structure_void"); - } - - /** - * The .iob V2 format stores the palette count, palette indices, and block coordinates as - * shorts. Values beyond the short range used to wrap silently and corrupt the object; every - * write path now rejects them with a descriptive error before any byte is written. - */ - static void validateWritable(IrisObject self) throws IOException { - KList palette = new KList<>(); - for (PlatformBlockState i : self.blocks.values()) { - palette.addIfMissing(i.key()); - } - if (palette.size() > MAX_PALETTE_ENTRIES) { - throw new IOException("Object '" + self.getLoadKey() + "' has " + palette.size() - + " distinct block states; the .iob format supports at most " + MAX_PALETTE_ENTRIES + "."); - } - for (var entry : self.blocks) { - requireShortCoordinates(self, "block", entry.getKey()); - } - for (var entry : self.states) { - requireShortCoordinates(self, "tile", entry.getKey()); - } - } - - private static void requireShortCoordinates(IrisObject self, String kind, IrisBlockVector position) throws IOException { - requireShort(self, kind, "x", position.getBlockX(), position); - requireShort(self, kind, "y", position.getBlockY(), position); - requireShort(self, kind, "z", position.getBlockZ(), position); - } - - private static void requireShort(IrisObject self, String kind, String axis, int value, IrisBlockVector position) throws IOException { - if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) { - throw new IOException("Object '" + self.getLoadKey() + "' " + kind + " at (" + position.getBlockX() - + "," + position.getBlockY() + "," + position.getBlockZ() - + ") exceeds the .iob coordinate range of ±32767 on the " + axis + " axis (" + value + ")."); - } - } - - static void write(IrisObject self, OutputStream o) throws IOException { - validateWritable(self); - writeValidated(self, o); - } - - private static void writeValidated(IrisObject self, OutputStream o) throws IOException { - DataOutputStream dos = new DataOutputStream(o); - dos.writeInt(self.w); - dos.writeInt(self.h); - dos.writeInt(self.d); - dos.writeUTF("Iris V2 IOB;"); - KList palette = new KList<>(); - - for (PlatformBlockState i : self.blocks.values()) { - palette.addIfMissing(i.key()); - } - - dos.writeShort(palette.size()); - - for (String i : palette) { - dos.writeUTF(i); - } - - dos.writeInt(self.blocks.size()); - - for (var entry : self.blocks) { - var i = entry.getKey(); - dos.writeShort(i.getBlockX()); - dos.writeShort(i.getBlockY()); - dos.writeShort(i.getBlockZ()); - dos.writeShort(palette.indexOf(entry.getValue().key())); - } - - dos.writeInt(self.states.size()); - for (var entry : self.states) { - var i = entry.getKey(); - dos.writeShort(i.getBlockX()); - dos.writeShort(i.getBlockY()); - dos.writeShort(i.getBlockZ()); - entry.getValue().toBinary(dos); - } - } - - static void write(IrisObject self, OutputStream o, VolmitSender sender) throws IOException { - validateWritable(self); - writeValidated(self, o, sender); - } - - private static void writeValidated(IrisObject self, OutputStream o, VolmitSender sender) throws IOException { - AtomicReference ref = new AtomicReference<>(); - CountDownLatch latch = new CountDownLatch(1); - new Job() { - private volatile int total = self.blocks.size() * 3 + self.states.size(); - private volatile int c = 0; - - @Override - public String getName() { - return IrisLanguage.text(RuntimeUiMessages.JOB_SAVING_OBJECT); - } - - @Override - public void execute() { - try { - DataOutputStream dos = new DataOutputStream(o); - dos.writeInt(self.w); - dos.writeInt(self.h); - dos.writeInt(self.d); - dos.writeUTF("Iris V2 IOB;"); - - KList palette = new KList<>(); - - for (PlatformBlockState i : self.blocks.values()) { - palette.addIfMissing(i.key()); - ++c; - } - total -= self.blocks.size() - palette.size(); - - dos.writeShort(palette.size()); - - for (String i : palette) { - dos.writeUTF(i); - ++c; - } - - dos.writeInt(self.blocks.size()); - - for (var entry : self.blocks) { - var i = entry.getKey(); - dos.writeShort(i.getBlockX()); - dos.writeShort(i.getBlockY()); - dos.writeShort(i.getBlockZ()); - dos.writeShort(palette.indexOf(entry.getValue().key())); - ++c; - } - - dos.writeInt(self.states.size()); - for (var entry : self.states) { - var i = entry.getKey(); - dos.writeShort(i.getBlockX()); - dos.writeShort(i.getBlockY()); - dos.writeShort(i.getBlockZ()); - entry.getValue().toBinary(dos); - ++c; - } - } catch (IOException e) { - ref.set(e); - } finally { - latch.countDown(); - } - } - - @Override - public void completeWork() {} - - @Override - public int getTotalWork() { - return total; - } - - @Override - public int getWorkCompleted() { - return c; - } - }.execute(sender, true, () -> {}); - - try { - latch.await(); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IOException("Interrupted while writing object", interrupted); - } - if (ref.get() != null) - throw ref.get(); - } - - static void write(IrisObject self, File file) throws IOException { - if (file == null) { - return; - } - - // Validate before opening the stream: FileOutputStream truncates, and a rejected - // object must leave the existing .iob untouched. - validateWritable(self); - try (FileOutputStream out = new FileOutputStream(file)) { - writeValidated(self, out); - } - } - - static void write(IrisObject self, File file, VolmitSender sender) throws IOException { - if (file == null) { - return; - } - - validateWritable(self); - try (FileOutputStream out = new FileOutputStream(file)) { - writeValidated(self, out, sender); - } - } - - private static class HeaderException extends IOException { - public HeaderException() { - super("Invalid Header"); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectRotation.java b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectRotation.java deleted file mode 100644 index 8f613a141..000000000 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectRotation.java +++ /dev/null @@ -1,518 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.prefab; - -import art.arcane.iris.builtin.prepare.AxisRotationClamp; -import art.arcane.iris.engine.object.value.IrisDirection; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.platform.bukkit.BukkitBlockState; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.math.IrisBlockVector; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.collection.KMap; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.Axis; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.MultipleFacing; -import org.bukkit.block.data.Orientable; -import org.bukkit.block.data.Rotatable; -import org.bukkit.block.data.type.RedstoneWire; -import org.bukkit.block.data.type.Wall; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -@Snippet("object-rotator") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Configures rotation for iris") -@Data -public class IrisObjectRotation { - private static volatile StateRotator PLATFORM_ROTATOR = null; - - public interface StateRotator { - PlatformBlockState rotate(IrisObjectRotation rotation, PlatformBlockState state, int spinx, int spiny, int spinz); - } - - public static synchronized StateRotator bindPlatformRotator(StateRotator rotator) { - StateRotator previous = PLATFORM_ROTATOR; - PLATFORM_ROTATOR = Objects.requireNonNull(rotator, "rotator"); - return previous; - } - - public static synchronized void restorePlatformRotator(StateRotator rotator) { - PLATFORM_ROTATOR = rotator; - } - - private static final class Faces { - private static final List WALL_FACES = List.of(BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST); - } - - @Desc("If this rotator is enabled or not") - private boolean enabled = true; - - @Desc("The x axis rotation") - private AxisRotationClamp xAxis = new AxisRotationClamp(); - - @Desc("The y axis rotation") - private AxisRotationClamp yAxis = AxisRotationClamp.of(true, false, 0, 0, 90); - - @Desc("The z axis rotation") - private AxisRotationClamp zAxis = new AxisRotationClamp(); - - public static IrisObjectRotation xFlip180() { - IrisObjectRotation rt = new IrisObjectRotation(); - rt.setEnabled(true); - rt.setXAxis(AxisRotationClamp.locked(true, 180, 0)); - rt.setYAxis(new AxisRotationClamp()); - rt.setZAxis(new AxisRotationClamp()); - return rt; - } - - public static IrisObjectRotation xFlip180RandomY() { - IrisObjectRotation rt = xFlip180(); - rt.setYAxis(AxisRotationClamp.of(true, false, 0, 0, 90)); - return rt; - } - - public static IrisObjectRotation xFlip180WithY(double y) { - IrisObjectRotation rt = xFlip180(); - rt.setYAxis(AxisRotationClamp.locked(true, y, 90)); - return rt; - } - - public static IrisObjectRotation of(double x, double y, double z) { - IrisObjectRotation rt = new IrisObjectRotation(); - rt.setEnabled(x != 0 || y != 0 || z != 0); - rt.setXAxis(AxisRotationClamp.locked(x != 0, x, 90)); - rt.setYAxis(AxisRotationClamp.locked(y != 0, y, 90)); - rt.setZAxis(AxisRotationClamp.locked(z != 0, z, 90)); - - return rt; - } - - public double getYRotation(int spin) { - return getRotation(spin, yAxis); - } - - public double getXRotation(int spin) { - return getRotation(spin, xAxis); - } - - public double getZRotation(int spin) { - return getRotation(spin, zAxis); - } - - public IrisObject rotateCopy(IrisObject e) { - if (e == null) { - return null; - } - - return e.rotateCopy(this); - } - - public IrisBlockVector rotate(IrisBlockVector direction) { - return rotate(direction, 0, 0, 0); - } - - public IrisDirection rotate(IrisDirection direction) { - IrisBlockVector v = rotate(new IrisBlockVector(direction.x(), direction.y(), direction.z())); - double m = Double.MAX_VALUE; - IrisDirection s = null; - - for (IrisDirection i : IrisDirection.values()) { - double g = new IrisBlockVector(i.x(), i.y(), i.z()).distance(v); - - if (g < m) { - m = g; - s = i; - } - } - - return s; - } - - public double getRotation(int spin, AxisRotationClamp clamp) { - if (!enabled) { - return 0; - } - - if (!clamp.enabled()) { - return 0; - } - - return clamp.getRadians(spin); - } - - public BlockFace getFace(IrisBlockVector v) { - int x = (int) Math.round(v.getX()); - int y = (int) Math.round(v.getY()); - int z = (int) Math.round(v.getZ()); - - if (x == 0 && z == -1) { - return BlockFace.NORTH; - } - - if (x == 0 && z == 1) { - return BlockFace.SOUTH; - } - - if (x == 1 && z == 0) { - return BlockFace.EAST; - } - - if (x == -1 && z == 0) { - return BlockFace.WEST; - } - - if (y > 0) { - return BlockFace.UP; - } - - if (y < 0) { - return BlockFace.DOWN; - } - - return BlockFace.SOUTH; - } - - public BlockFace getHexFace(IrisBlockVector v) { - int x = v.getBlockX(); - int y = v.getBlockY(); - int z = v.getBlockZ(); - - if (x == 0 && z == -1) return BlockFace.NORTH; - if (x == 1 && z == -2) return BlockFace.NORTH_NORTH_EAST; - if (x == 1 && z == -1) return BlockFace.NORTH_EAST; - if (x == 2 && z == -1) return BlockFace.EAST_NORTH_EAST; - if (x == 1 && z == 0) return BlockFace.EAST; - if (x == 2 && z == 1) return BlockFace.EAST_SOUTH_EAST; - if (x == 1 && z == 1) return BlockFace.SOUTH_EAST; - if (x == 1 && z == 2) return BlockFace.SOUTH_SOUTH_EAST; - if (x == 0 && z == 1) return BlockFace.SOUTH; - if (x == -1 && z == 2) return BlockFace.SOUTH_SOUTH_WEST; - if (x == -1 && z == 1) return BlockFace.SOUTH_WEST; - if (x == -2 && z == 1) return BlockFace.WEST_SOUTH_WEST; - if (x == -1 && z == 0) return BlockFace.WEST; - if (x == -2 && z == -1) return BlockFace.WEST_NORTH_WEST; - if (x == -1 && z == -1) return BlockFace.NORTH_WEST; - if (x == -1 && z == -2) return BlockFace.NORTH_NORTH_WEST; - - if (y > 0) { - return BlockFace.UP; - } - - if (y < 0) { - return BlockFace.DOWN; - } - - return BlockFace.SOUTH; - } - - public BlockFace faceForAxis(Axis axis) { - return switch (axis) { - case X -> BlockFace.EAST; - case Y -> BlockFace.UP; - case Z -> BlockFace.NORTH; - }; - - } - - public Axis axisFor(BlockFace f) { - return switch (f) { - case NORTH, SOUTH -> Axis.Z; - case EAST, WEST -> Axis.X; - default -> Axis.Y; - }; - - } - - public Axis axisFor2D(BlockFace f) { - return switch (f) { - case EAST, WEST, UP, DOWN -> Axis.X; - default -> Axis.Z; - }; - - } - - public PlatformBlockState rotate(PlatformBlockState state, int spinx, int spiny, int spinz) { - if (state == null) { - return null; - } - - StateRotator rotator = PLATFORM_ROTATOR; - if (rotator != null) { - return rotator.rotate(this, state, spinx, spiny, spinz); - } - - BlockData original = (BlockData) state.nativeHandle(); - if (!canRotate() || !canRotateBlockData(original)) { - return state; - } - - BlockData raw = original.clone(); - BlockData rotated = rotate(raw, spinx, spiny, spinz); - return rotated == null ? null : BukkitBlockState.of(rotated); - } - - private static boolean canRotateBlockData(BlockData data) { - return data instanceof Directional - || data instanceof Rotatable - || data instanceof Orientable - || data instanceof MultipleFacing - || data instanceof Wall - || data instanceof RedstoneWire; - } - - public BlockData rotate(BlockData dd, int spinxx, int spinyy, int spinzz) { - BlockData d = dd; - try { - int spinx = (int) (90D * (Math.ceil(Math.abs((spinxx % 360D) / 90D)))); - int spiny = (int) (90D * (Math.ceil(Math.abs((spinyy % 360D) / 90D)))); - int spinz = (int) (90D * (Math.ceil(Math.abs((spinzz % 360D) / 90D)))); - - if (!canRotate()) { - return d; - } - - if (d instanceof Directional g) { - BlockFace f = g.getFacing(); - IrisBlockVector bv = new IrisBlockVector(f.getModX(), f.getModY(), f.getModZ()); - bv = rotate(bv.clone(), spinx, spiny, spinz); - BlockFace t = getFace(bv); - - if (g.getFaces().contains(t)) { - g.setFacing(t); - } else if (!g.getMaterial().isSolid()) { - d = null; - } - } else if (d instanceof Rotatable g) { - BlockFace f = g.getRotation(); - - IrisBlockVector bv = new IrisBlockVector(f.getModX(), 0, f.getModZ()); - bv = rotate(bv.clone(), spinx, spiny, spinz); - BlockFace face = getHexFace(bv); - - g.setRotation(face); - - } else if (d instanceof Orientable g) { - BlockFace f = getFace(g.getAxis()); - IrisBlockVector bv = new IrisBlockVector(f.getModX(), f.getModY(), f.getModZ()); - bv = rotate(bv.clone(), spinx, spiny, spinz); - Axis a = getAxis(bv); - - if (!a.equals(g.getAxis()) && g.getAxes().contains(a)) { - g.setAxis(a); - } - } else if (d instanceof MultipleFacing g) { - List faces = new KList<>(); - - for (BlockFace i : g.getFaces()) { - IrisBlockVector bv = new IrisBlockVector(i.getModX(), i.getModY(), i.getModZ()); - bv = rotate(bv.clone(), spinx, spiny, spinz); - BlockFace r = getFace(bv); - - if (g.getAllowedFaces().contains(r)) { - faces.add(r); - } - } - - for (BlockFace i : g.getFaces()) { - g.setFace(i, false); - } - - for (BlockFace i : faces) { - g.setFace(i, true); - } - } else if (d instanceof Wall wall) { - KMap faces = new KMap<>(); - - for (BlockFace i : Faces.WALL_FACES) { - Wall.Height h = wall.getHeight(i); - IrisBlockVector bv = new IrisBlockVector(i.getModX(), i.getModY(), i.getModZ()); - bv = rotate(bv.clone(), spinx, spiny, spinz); - BlockFace r = getFace(bv); - if (Faces.WALL_FACES.contains(r)) { - faces.put(r, h); - } - } - - for (BlockFace i : Faces.WALL_FACES) { - wall.setHeight(i, faces.getOrDefault(i, Wall.Height.NONE)); - } - } else if (d instanceof RedstoneWire wire) { - Map faces = new HashMap<>(); - - Set allowed = wire.getAllowedFaces(); - for (BlockFace i : allowed) { - RedstoneWire.Connection connection = wire.getFace(i); - IrisBlockVector bv = new IrisBlockVector(i.getModX(), i.getModY(), i.getModZ()); - bv = rotate(bv.clone(), spinx, spiny, spinz); - BlockFace r = getFace(bv); - if (allowed.contains(r)) - faces.put(r, connection); - } - - for (BlockFace i : allowed) { - wire.setFace(i, faces.getOrDefault(i, RedstoneWire.Connection.NONE)); - } - } - } catch (Throwable e) { - IrisLogging.reportError(e); - - } - - return d; - } - - public Axis getAxis(IrisBlockVector v) { - if (Math.abs(v.getBlockX()) > Math.max(Math.abs(v.getBlockY()), Math.abs(v.getBlockZ()))) { - return Axis.X; - } - - if (Math.abs(v.getBlockY()) > Math.max(Math.abs(v.getBlockX()), Math.abs(v.getBlockZ()))) { - return Axis.Y; - } - - if (Math.abs(v.getBlockZ()) > Math.max(Math.abs(v.getBlockX()), Math.abs(v.getBlockY()))) { - return Axis.Z; - } - - return Axis.Y; - } - - private BlockFace getFace(Axis axis) { - return switch (axis) { - case X -> BlockFace.EAST; - case Y -> BlockFace.UP; - case Z -> BlockFace.SOUTH; - }; - } - - public IrisPosition rotate(IrisPosition b) { - return rotate(b, 0, 0, 0); - } - - public IrisPosition rotate(IrisPosition b, int spinx, int spiny, int spinz) { - IrisBlockVector v = rotate(new IrisBlockVector(b.getX(), b.getY(), b.getZ()), spinx, spiny, spinz); - return new IrisPosition(v.getBlockX(), v.getBlockY(), v.getBlockZ()); - } - - public IrisBlockVector rotate(IrisBlockVector b, int spinx, int spiny, int spinz) { - if (!canRotate()) { - return b; - } - - IrisBlockVector v = b.clone(); - - if (canRotateX()) { - if (getXAxis().isLocked()) { - if (Math.abs(getXAxis().max()) % 360D == 180D) { - v.setZ(-v.getZ()); - v.setY(-v.getY()); - } else if (getXAxis().max() % 360D == 90D || getXAxis().max() % 360D == -270D) { - double z = v.getZ(); - v.setZ(v.getY()); - v.setY(-z); - } else if (getXAxis().max() == -90D || getXAxis().max() % 360D == 270D) { - double z = v.getZ(); - v.setZ(-v.getY()); - v.setY(z); - } else { - v.rotateAroundX(getXRotation(spinx)); - } - } else { - v.rotateAroundX(getXRotation(spinx)); - } - } - - if (canRotateZ()) { - if (getZAxis().isLocked()) { - if (Math.abs(getZAxis().max()) % 360D == 180D) { - v.setY(-v.getY()); - v.setX(-v.getX()); - } else if (getZAxis().max() % 360D == 90D || getZAxis().max() % 360D == -270D) { - double y = v.getY(); - v.setY(v.getX()); - v.setX(-y); - } else if (getZAxis().max() == -90D || getZAxis().max() % 360D == 270D) { - double y = v.getY(); - v.setY(-v.getX()); - v.setX(y); - } else { - v.rotateAroundZ(getZRotation(spinz)); - } - } else { - v.rotateAroundZ(getZRotation(spinz)); - } - } - - if (canRotateY()) { - if (getYAxis().isLocked()) { - if (Math.abs(getYAxis().max()) % 360D == 180D) { - v.setX(-v.getX()); - v.setZ(-v.getZ()); - } else if (getYAxis().max() % 360D == 90D || getYAxis().max() % 360D == -270D) { - double x = v.getX(); - v.setX(v.getZ()); - v.setZ(-x); - } else if (getYAxis().max() == -90D || getYAxis().max() % 360D == 270D) { - double x = v.getX(); - v.setX(-v.getZ()); - v.setZ(x); - } else { - v.rotateAroundY(getYRotation(spiny)); - } - } else { - v.rotateAroundY(getYRotation(spiny)); - } - } - - return v; - } - - public boolean canRotateX() { - return enabled && xAxis.enabled(); - } - - public boolean canRotateY() { - return enabled && yAxis.enabled(); - } - - public boolean canRotateZ() { - return enabled && zAxis.enabled(); - } - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean canRotate() { - return canRotateX() || canRotateY() || canRotateZ(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectScale.java b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectScale.java deleted file mode 100644 index 55498896a..000000000 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectScale.java +++ /dev/null @@ -1,380 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.prefab; - -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.math.Vector3i; -import art.arcane.volmlib.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.lang.ref.ReferenceQueue; -import java.lang.ref.WeakReference; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; - -@Snippet("object-scale") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Scale objects") -@Data -public class IrisObjectScale { - private static final long CACHE_MIN_ESTIMATED_BYTES = 16L * 1024L * 1024L; - private static final long CACHE_MAX_ESTIMATED_BYTES = 64L * 1024L * 1024L; - private static final long CACHE_ENTRY_ESTIMATED_BYTES = 512L; - private static final long CACHE_VARIANT_ESTIMATED_BYTES = 256L; - private static final long CACHE_ESTIMATED_BYTES_PER_VOXEL = 128L; - private static final int CACHE_LOAD_LOCK_COUNT = 256; - - @MinNumber(0.01) - @MaxNumber(50) - @Desc("Fixed scale multiplier for this object. 0.5 shrinks to half size, 2.0 doubles the size. When set to anything other than 1, this overrides minimumScale and maximumScale. Leave at 1 to use the minimumScale/maximumScale range.") - private double size = 1; - - @MinNumber(1) - @MaxNumber(32) - @Desc("Iris Objects are scaled and cached to speed up placements. Because of this extra memory is used, so we evenly distribute variations across the defined scale range, then pick one randomly. If the differences is small, use a lower number. For more possibilities on the scale spectrum, increase this at the cost of memory.") - private int variations = 7; - - @MinNumber(0.01) - @MaxNumber(50) - @Desc("The minimum scale. Used when size is 1 to pick a random scale per placement.") - private double minimumScale = 1; - - @MinNumber(0.01) - @MaxNumber(50) - @Desc("The maximum scale. Used when size is 1 to pick a random scale per placement.") - private double maximumScale = 1; - - @Desc("If this object is scaled up beyond its origin size, specify a 3D interpolator. NONE keeps blocky scaled output, TRILINEAR (LERP) smooths with linear interpolation, TRICUBIC and TRIHERMITE produce smoother but slower output.") - private IrisObjectPlacementScaleInterpolator interpolation = IrisObjectPlacementScaleInterpolator.NONE; - - public boolean shouldScale() { - if (size != 1) { - return true; - } - if (variations <= 0) { - return false; - } - return minimumScale != 1 || maximumScale != 1; - } - - public int getMaxSizeFor(int indim) { - return (int) Math.ceil(getMaxScale() * indim); - } - - public double getMaxScale() { - if (size != 1) { - return size; - } - return Math.max(minimumScale, maximumScale); - } - - /** The scaled variant of {@code origin} this scale picks, built once per world and kept in the world's cache. */ - public IrisObject get(RNG rng, IrisObject origin, Engine engine) { - if (origin == null) { - return null; - } - - ScaleRequest request = snapshotRequest(); - if (!request.shouldScale()) { - return origin; - } - - int variantIndex = request.selectVariant(rng); - ScaleCache cache = cacheOf(engine); - CacheKey key = cache.key(origin, request, variantIndex); - IrisObject cached = cache.lookup(key); - if (cached != null) { - return cached; - } - - synchronized (cache.loadLock(key)) { - IrisObject afterWait = cache.lookup(key); - if (afterWait != null) { - return afterWait; - } - - IrisObject variant = origin.scaled(request.scaleAt(variantIndex), request.interpolation()); - long estimatedBytes = estimateVariant(variant); - return cache.putIfAbsent(key, variant, estimatedBytes); - } - } - - static ScaleCache cacheOf(Engine engine) { - return engine.getGeneration().state(ScaleCache.class, world -> new ScaleCache(resolveCacheMaximumEstimatedBytes())); - } - - public boolean canScaleBeyond() { - return shouldScale() && getMaxScale() > 1; - } - - private ScaleRequest snapshotRequest() { - IrisObjectPlacementScaleInterpolator configuredInterpolation = interpolation == null - ? IrisObjectPlacementScaleInterpolator.NONE - : interpolation; - return new ScaleRequest(size, minimumScale, maximumScale, variations, configuredInterpolation); - } - - private static long estimateVariant(IrisObject variant) { - long width = Math.max(1L, variant.getW()); - long height = Math.max(1L, variant.getH()); - long depth = Math.max(1L, variant.getD()); - long volume = saturatedMultiply(saturatedMultiply(width, height), depth); - long populatedVoxels = saturatedAdd(variant.getBlocks().size(), variant.getStates().size()); - long voxelBytes = saturatedMultiply(Math.max(volume, populatedVoxels), CACHE_ESTIMATED_BYTES_PER_VOXEL); - return saturatedAdd(CACHE_ENTRY_ESTIMATED_BYTES, - saturatedAdd(CACHE_VARIANT_ESTIMATED_BYTES, voxelBytes)); - } - - private static long saturatedAdd(long first, long second) { - if (first >= Long.MAX_VALUE - second) { - return Long.MAX_VALUE; - } - return first + second; - } - - private static long saturatedMultiply(long first, long second) { - if (first == 0L || second == 0L) { - return 0L; - } - if (first > Long.MAX_VALUE / second) { - return Long.MAX_VALUE; - } - return first * second; - } - - private static long resolveCacheMaximumEstimatedBytes() { - long heapShare = Runtime.getRuntime().maxMemory() / 32L; - return Math.max(CACHE_MIN_ESTIMATED_BYTES, Math.min(CACHE_MAX_ESTIMATED_BYTES, heapShare)); - } - - record ScaleRequest(double size, double minimumScale, double maximumScale, int variations, - IrisObjectPlacementScaleInterpolator interpolation) { - boolean shouldScale() { - if (size != 1D) { - return true; - } - return variations > 0 && (minimumScale != 1D || maximumScale != 1D); - } - - int variantCount() { - if (size != 1D || minimumScale == maximumScale) { - return 1; - } - return Math.max(1, Math.min(variations, 32)); - } - - int selectVariant(RNG rng) { - int count = variantCount(); - return count == 1 ? 0 : rng.nextInt(count); - } - - double scaleAt(int index) { - if (size != 1D) { - return size; - } - if (minimumScale == maximumScale) { - return minimumScale; - } - return minimumScale + (((maximumScale - minimumScale) / variantCount()) * index); - } - } - - static final class CacheKey extends WeakReference { - private final ScaleRequest request; - private final int variantIndex; - private final int originRevision; - private final int loadHashCode; - private final int hashCode; - - CacheKey(IrisObject origin, ScaleRequest request, int variantIndex) { - this(origin, request, variantIndex, null); - } - - CacheKey(IrisObject origin, ScaleRequest request, int variantIndex, - ReferenceQueue collectedOrigins) { - super(origin, collectedOrigins); - this.request = request; - this.variantIndex = variantIndex; - this.originRevision = originRevision(origin); - int result = System.identityHashCode(origin); - result = (31 * result) + originRevision; - result = (31 * result) + request.hashCode(); - this.loadHashCode = result; - this.hashCode = (31 * result) + variantIndex; - } - - boolean hasOrigin(IrisObject candidate) { - return get() == candidate; - } - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (!(object instanceof CacheKey other)) { - return false; - } - IrisObject origin = get(); - return origin != null - && origin == other.get() - && originRevision == other.originRevision - && request.equals(other.request) - && variantIndex == other.variantIndex; - } - - @Override - public int hashCode() { - return hashCode; - } - - int loadHashCode() { - return loadHashCode; - } - - private static int originRevision(IrisObject origin) { - origin.readLock.lock(); - try { - int result = origin.getW(); - result = (31 * result) + origin.getH(); - result = (31 * result) + origin.getD(); - result = (31 * result) + System.identityHashCode(origin.getBlocks()); - result = (31 * result) + System.identityHashCode(origin.getStates()); - result = (31 * result) + Long.hashCode(origin.getBlocks().modificationRevision()); - result = (31 * result) + Long.hashCode(origin.getStates().modificationRevision()); - Vector3i center = origin.getCenter(); - if (center != null) { - result = (31 * result) + center.getX(); - result = (31 * result) + center.getY(); - result = (31 * result) + center.getZ(); - } - return result; - } finally { - origin.readLock.unlock(); - } - } - } - - static final class ScaleCache { - private final long maximumEstimatedBytes; - private final LinkedHashMap entries; - private final Object[] loadLocks; - private final ReferenceQueue collectedOrigins; - private long estimatedBytes; - - ScaleCache(long maximumEstimatedBytes) { - if (maximumEstimatedBytes <= 0L) { - throw new IllegalArgumentException("maximumEstimatedBytes must be positive"); - } - this.maximumEstimatedBytes = maximumEstimatedBytes; - this.entries = new LinkedHashMap<>(256, 0.75F, true); - this.loadLocks = new Object[CACHE_LOAD_LOCK_COUNT]; - this.collectedOrigins = new ReferenceQueue<>(); - for (int index = 0; index < loadLocks.length; index++) { - loadLocks[index] = new Object(); - } - } - - CacheKey key(IrisObject origin, ScaleRequest request, int variantIndex) { - return new CacheKey(origin, request, variantIndex, collectedOrigins); - } - - Object loadLock(CacheKey key) { - return loadLocks[key.loadHashCode() & (loadLocks.length - 1)]; - } - - synchronized IrisObject lookup(CacheKey key) { - drainCollectedOrigins(); - CacheValue value = entries.get(key); - return value == null ? null : value.variant(); - } - - synchronized IrisObject putIfAbsent(CacheKey key, IrisObject variant, long entryEstimatedBytes) { - drainCollectedOrigins(); - CacheValue present = entries.get(key); - if (present != null) { - return present.variant(); - } - if (entryEstimatedBytes > maximumEstimatedBytes) { - return variant; - } - - entries.put(key, new CacheValue(variant, entryEstimatedBytes)); - estimatedBytes += entryEstimatedBytes; - evictToBudget(); - return variant; - } - - synchronized int size() { - drainCollectedOrigins(); - return entries.size(); - } - - synchronized long estimatedBytes() { - drainCollectedOrigins(); - return estimatedBytes; - } - - long maximumEstimatedBytes() { - return maximumEstimatedBytes; - } - - synchronized boolean containsOrigin(IrisObject origin) { - drainCollectedOrigins(); - for (CacheKey key : entries.keySet()) { - if (key.hasOrigin(origin)) { - return true; - } - } - return false; - } - - private void evictToBudget() { - Iterator> iterator = entries.entrySet().iterator(); - while (estimatedBytes > maximumEstimatedBytes && iterator.hasNext()) { - Map.Entry entry = iterator.next(); - estimatedBytes -= entry.getValue().estimatedBytes(); - iterator.remove(); - } - } - - private void drainCollectedOrigins() { - CacheKey collected; - while ((collected = (CacheKey) collectedOrigins.poll()) != null) { - CacheValue removed = entries.remove(collected); - if (removed != null) { - estimatedBytes -= removed.estimatedBytes(); - } - } - } - } - - record CacheValue(IrisObject variant, long estimatedBytes) { - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectShaping.java b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectShaping.java deleted file mode 100644 index 19ad00a47..000000000 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectShaping.java +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.prefab; - -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.data.VectorMap; -import art.arcane.volmlib.util.math.IrisBlockVector; -import art.arcane.volmlib.util.math.IrisVector; -import art.arcane.volmlib.util.math.Vector3i; -import art.arcane.iris.util.common.parallel.BurstExecutor; -import art.arcane.iris.util.common.parallel.MultiBurst; -import art.arcane.volmlib.util.format.Form; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Volume shaping for {@link IrisObject}: smart boring, shrinkwrapping, compaction and the shared block - * classification helpers used by placement. - */ -public final class IrisObjectShaping { - private IrisObjectShaping() { - } - - public static void ensureSmartBored(IrisObject self) { - if (self.smartBored) { - return; - } - - // Whole computation under the object's write lock: two racing callers would otherwise - // both compute, with the loser reading self.blocks while the winner merges into it. - self.writeLock.lock(); - try { - if (self.smartBored) { - return; - } - ensureSmartBoredLocked(self); - } finally { - self.writeLock.unlock(); - } - } - - private static void ensureSmartBoredLocked(IrisObject self) { - PrecisionStopwatch p = PrecisionStopwatch.start(); - PlatformBlockState vair = IrisObject.States.VAIR; - AtomicInteger applied = new AtomicInteger(); - IrisBlockVector max = new IrisBlockVector(Double.MIN_VALUE, Double.MIN_VALUE, Double.MIN_VALUE); - IrisBlockVector min = new IrisBlockVector(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE); - VectorMap source; - self.readLock.lock(); - try { - if (self.blocks.isEmpty()) { - IrisLogging.warn("Cannot Smart Bore " + self.getLoadKey() + " because it has 0 blocks in it."); - self.smartBored = true; - return; - } - - source = self.blocks; - - for (IrisBlockVector i : self.blocks.keys()) { - max.setX(Math.max(i.getX(), max.getX())); - min.setX(Math.min(i.getX(), min.getX())); - max.setY(Math.max(i.getY(), max.getY())); - min.setY(Math.min(i.getY(), min.getY())); - max.setZ(Math.max(i.getZ(), max.getZ())); - min.setZ(Math.min(i.getZ(), min.getZ())); - } - } finally { - self.readLock.unlock(); - } - - VectorMap bore = new VectorMap<>(); - // Inline on purpose: the three axis passes read AND write the shared bore map, so the - // bored volume must come from a fixed X->Y->Z order on the calling (lock-owning) - // thread, not from pool scheduling. This matches what burst-worker callers (studio, - // generation threads) already produced, so output is unchanged where it was stable. - BurstExecutor burst = MultiBurst.burst.burst(); - burst.setMulticore(false); - - // Smash X - for (int rayY = min.getBlockY(); rayY <= max.getBlockY(); rayY++) { - int finalRayY = rayY; - burst.queue(() -> { - for (int rayZ = min.getBlockZ(); rayZ <= max.getBlockZ(); rayZ++) { - int start = Integer.MAX_VALUE; - int end = Integer.MIN_VALUE; - - for (int ray = min.getBlockX(); ray <= max.getBlockX(); ray++) { - if (boreContains(source, bore, new IrisBlockVector(ray, finalRayY, rayZ))) { - start = Math.min(ray, start); - end = Math.max(ray, end); - } - } - - if (start != Integer.MAX_VALUE && end != Integer.MIN_VALUE) { - for (int i = start; i <= end; i++) { - boreCell(source, bore, new IrisBlockVector(i, finalRayY, rayZ), vair, applied); - } - } - } - }); - } - - // Smash Y - for (int rayX = min.getBlockX(); rayX <= max.getBlockX(); rayX++) { - int finalRayX = rayX; - burst.queue(() -> { - for (int rayZ = min.getBlockZ(); rayZ <= max.getBlockZ(); rayZ++) { - int start = Integer.MAX_VALUE; - int end = Integer.MIN_VALUE; - - for (int ray = min.getBlockY(); ray <= max.getBlockY(); ray++) { - if (boreContains(source, bore, new IrisBlockVector(finalRayX, ray, rayZ))) { - start = Math.min(ray, start); - end = Math.max(ray, end); - } - } - - if (start != Integer.MAX_VALUE && end != Integer.MIN_VALUE) { - for (int i = start; i <= end; i++) { - boreCell(source, bore, new IrisBlockVector(finalRayX, i, rayZ), vair, applied); - } - } - } - }); - } - - // Smash Z - for (int rayX = min.getBlockX(); rayX <= max.getBlockX(); rayX++) { - int finalRayX = rayX; - burst.queue(() -> { - for (int rayY = min.getBlockY(); rayY <= max.getBlockY(); rayY++) { - int start = Integer.MAX_VALUE; - int end = Integer.MIN_VALUE; - - for (int ray = min.getBlockZ(); ray <= max.getBlockZ(); ray++) { - if (boreContains(source, bore, new IrisBlockVector(finalRayX, rayY, ray))) { - start = Math.min(ray, start); - end = Math.max(ray, end); - } - } - - if (start != Integer.MAX_VALUE && end != Integer.MIN_VALUE) { - for (int i = start; i <= end; i++) { - boreCell(source, bore, new IrisBlockVector(finalRayX, rayY, i), vair, applied); - } - } - } - }); - } - - burst.complete(); - - self.writeLock.lock(); - try { - if (!self.smartBored) { - bore.forEach((v, s) -> self.blocks.computeIfAbsent(v, (vv) -> s)); - self.forgetDerivedShapes(); - self.smartBored = true; - } - } finally { - self.writeLock.unlock(); - } - - IrisLogging.debug("Smart Bore: " + self.getLoadKey() + " in " + Form.duration(p.getMilliseconds(), 2) + " (" + Form.f(applied.get()) + ")"); - } - - private static boolean boreContains(VectorMap source, VectorMap bore, IrisBlockVector v) { - return source.containsKey(v) || bore.containsKey(v); - } - - private static void boreCell(VectorMap source, VectorMap bore, IrisBlockVector v, PlatformBlockState vair, AtomicInteger applied) { - PlatformBlockState existing = source.get(v); - - if (existing == null) { - if (vair.equals(bore.get(v))) { - return; - } - - bore.computeIfAbsent(v, (vv) -> vair); - } else if (vair.equals(existing)) { - return; - } - - applied.getAndIncrement(); - } - - public static void shrinkwrap(IrisObject self) { - if (self.blocks.isEmpty()) return; - IrisBlockVector min = new IrisBlockVector(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); - IrisBlockVector max = new IrisBlockVector(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE); - - for (IrisBlockVector i : self.blocks.keys()) { - min.setX(Math.min(min.getX(), i.getX())); - min.setY(Math.min(min.getY(), i.getY())); - min.setZ(Math.min(min.getZ(), i.getZ())); - max.setX(Math.max(max.getX(), i.getX())); - max.setY(Math.max(max.getY(), i.getY())); - max.setZ(Math.max(max.getZ(), i.getZ())); - } - - // Compute into locals and assign every field in one block at the end, so a reader can - // never observe post-shrink dimensions paired with pre-shrink volume (or vice versa). - int w = max.getBlockX() - min.getBlockX() + 1; - int h = max.getBlockY() - min.getBlockY() + 1; - int d = max.getBlockZ() - min.getBlockZ() + 1; - Vector3i center = new Vector3i(w / 2, h / 2, d / 2); - - Vector3i offset = new Vector3i( - -center.getBlockX() - min.getBlockX(), - -center.getBlockY() - min.getBlockY(), - -center.getBlockZ() - min.getBlockZ() - ); - if (offset.getBlockX() == 0 && offset.getBlockY() == 0 && offset.getBlockZ() == 0) { - self.w = w; - self.h = h; - self.d = d; - self.center = center; - return; - } - - VectorMap b = new VectorMap<>(); - VectorMap s = new VectorMap<>(); - IrisBlockVector shift = new IrisBlockVector(offset.getX(), offset.getY(), offset.getZ()); - - self.blocks.forEach((vector, data) -> { - vector.add(shift); - b.put(vector, data); - }); - - self.states.forEach((vector, data) -> { - vector.add(shift); - s.put(vector, data); - }); - - self.w = w; - self.h = h; - self.d = d; - self.center = center; - self.shrinkOffset = offset; - self.blocks = b; - self.states = s; - self.forgetDerivedShapes(); - } - - public static void clean(IrisObject self) { - VectorMap d = new VectorMap<>(); - d.putAll(self.blocks); - - VectorMap dx = new VectorMap<>(); - dx.putAll(self.states); - - self.blocks = d; - self.states = dx; - self.forgetDerivedShapes(); - } - - public static boolean shouldStilt(PlatformBlockState state) { - if (!state.isOccluding()) { - return false; - } - String material = materialKey(state); - if (material.endsWith("_stairs") || material.endsWith("_slab")) { - return false; - } - return !material.equals("minecraft:dirt_path"); - } - - public static String materialKey(PlatformBlockState state) { - String memoized = state.materialKey(); - if (memoized != null) { - return memoized; - } - String key = state.key(); - int bracket = key.indexOf('['); - return bracket < 0 ? key : key.substring(0, bracket); - } - - public static List blocksBetweenTwoPoints(IrisVector loc1, IrisVector loc2) { - List locations = new ArrayList<>(); - int topBlockX = Math.max(loc1.getBlockX(), loc2.getBlockX()); - int bottomBlockX = Math.min(loc1.getBlockX(), loc2.getBlockX()); - int topBlockY = Math.max(loc1.getBlockY(), loc2.getBlockY()); - int bottomBlockY = Math.min(loc1.getBlockY(), loc2.getBlockY()); - int topBlockZ = Math.max(loc1.getBlockZ(), loc2.getBlockZ()); - int bottomBlockZ = Math.min(loc1.getBlockZ(), loc2.getBlockZ()); - - for (int x = bottomBlockX; x <= topBlockX; x++) { - for (int z = bottomBlockZ; z <= topBlockZ; z++) { - for (int y = bottomBlockY; y <= topBlockY; y++) { - locations.add(new IrisBlockVector(x, y, z)); - } - } - } - return locations; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectTransforms.java b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectTransforms.java deleted file mode 100644 index ba0c7020d..000000000 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectTransforms.java +++ /dev/null @@ -1,370 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.prefab; - -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.data.VectorMap; -import art.arcane.volmlib.util.math.IrisBlockVector; -import art.arcane.volmlib.util.math.IrisVector; -import art.arcane.iris.util.project.interpolation.Interpolation3D; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; - -/** - * Geometric transforms for {@link IrisObject}: rotation, scaling and the interpolated upscalers. - */ -final class IrisObjectTransforms { - private IrisObjectTransforms() { - } - - static IrisObject rotateCopy(IrisObject self, IrisObjectRotation rt) { - IrisObject copy = self.copy(); - rotate(copy, rt, 0, 0, 0); - return copy; - } - - static void rotate(IrisObject self, IrisObjectRotation r, int spinx, int spiny, int spinz) { - self.writeLock.lock(); - try { - VectorMap d = new VectorMap<>(); - - for (var entry : self.blocks) { - d.put(r.rotate(entry.getKey(), spinx, spiny, spinz), r.rotate(entry.getValue(), spinx, spiny, spinz)); - } - - VectorMap dx = new VectorMap<>(); - - for (var entry : self.states) { - dx.put(r.rotate(entry.getKey(), spinx, spiny, spinz), entry.getValue()); - } - - self.blocks = d; - self.states = dx; - IrisObjectShaping.shrinkwrap(self); - self.surfaceSupportOffsets.reset(); - self.floatingFootprint.reset(); - } finally { - self.writeLock.unlock(); - } - } - - static IrisObject scaled(IrisObject self, double scale, IrisObjectPlacementScaleInterpolator interpolation) { - if (interpolation == null) { - interpolation = IrisObjectPlacementScaleInterpolator.NONE; - } - IrisVector sm1 = new IrisVector(scale - 1, scale - 1, scale - 1); - scale = Math.max(0.001, Math.min(50, scale)); - if (scale < 1) { - scale = scale - 0.0001; - } - - IrisPosition l1 = self.getAABB().max(); - IrisPosition l2 = self.getAABB().min(); - VectorMap placeBlock = new VectorMap<>(); - - IrisVector center = new IrisVector(self.getCenter().getX(), self.getCenter().getY(), self.getCenter().getZ()); - if (self.getH() == 2) { - center = center.setY(center.getBlockY() + 0.5); - } - if (self.getW() == 2) { - center = center.setX(center.getBlockX() + 0.5); - } - if (self.getD() == 2) { - center = center.setZ(center.getBlockZ() + 0.5); - } - - IrisObject oo = new IrisObject((int) Math.ceil((self.w * scale) + (scale * 2)), (int) Math.ceil((self.h * scale) + (scale * 2)), (int) Math.ceil((self.d * scale) + (scale * 2))); - oo.setLoadKey(self.getLoadKey()); - oo.setLoader(self.getLoader()); - oo.setLoadFile(self.getLoadFile()); - - self.readLock.lock(); - try { - for (var entry : self.blocks) { - PlatformBlockState bd = entry.getValue(); - placeBlock.put(entry.getKey().clone().add(IrisObject.HALF).subtract(center) - .multiply(scale).add(sm1).toBlockVector(), bd); - } - } finally { - self.readLock.unlock(); - } - - for (var entry : placeBlock) { - IrisBlockVector v = entry.getKey(); - if (scale > 1) { - for (IrisBlockVector vec : IrisObjectShaping.blocksBetweenTwoPoints(v.clone().add(center), v.clone().add(center).add(sm1))) { - oo.blocks.put(vec, entry.getValue()); - } - } else { - oo.setUnsigned(v.getBlockX(), v.getBlockY(), v.getBlockZ(), entry.getValue()); - } - } - - if (scale > 1) { - switch (interpolation) { - case TRILINEAR -> trilinear(oo, (int) Math.round(scale)); - case TRICUBIC -> tricubic(oo, (int) Math.round(scale)); - case TRIHERMITE -> trihermite(oo, (int) Math.round(scale)); - } - } - - return oo; - } - - static void trilinear(IrisObject self, int rad) { - self.writeLock.lock(); - try { - VectorMap v = self.blocks; - VectorMap b = new VectorMap<>(); - IrisPosition min = self.getAABB().min(); - IrisPosition max = self.getAABB().max(); - NearestBlockIndex nearestBlocks = NearestBlockIndex.create(v); - - for (int x = min.getX(); x <= max.getX(); x++) { - for (int y = min.getY(); y <= max.getY(); y++) { - for (int z = min.getZ(); z <= max.getZ(); z++) { - if (Interpolation3D.getTrilinear(x, y, z, rad, (xx, yy, zz) -> { - PlatformBlockState data = v.get(new IrisBlockVector((int) xx, (int) yy, (int) zz)); - - if (B.isAir(data)) { - return 0; - } - - return 1; - }) >= 0.5) { - b.put(new IrisBlockVector(x, y, z), nearestBlockData(v, nearestBlocks, x, y, z)); - } else { - b.put(new IrisBlockVector(x, y, z), IrisObject.States.AIR); - } - } - } - } - - self.blocks = b; - self.surfaceSupportOffsets.reset(); - self.floatingFootprint.reset(); - } finally { - self.writeLock.unlock(); - } - } - - static void tricubic(IrisObject self, int rad) { - self.writeLock.lock(); - try { - VectorMap v = self.blocks; - VectorMap b = new VectorMap<>(); - IrisPosition min = self.getAABB().min(); - IrisPosition max = self.getAABB().max(); - NearestBlockIndex nearestBlocks = NearestBlockIndex.create(v); - - for (int x = min.getX(); x <= max.getX(); x++) { - for (int y = min.getY(); y <= max.getY(); y++) { - for (int z = min.getZ(); z <= max.getZ(); z++) { - if (Interpolation3D.getTricubic(x, y, z, rad, (xx, yy, zz) -> { - PlatformBlockState data = v.get(new IrisBlockVector((int) xx, (int) yy, (int) zz)); - - if (B.isAir(data)) { - return 0; - } - - return 1; - }) >= 0.5) { - b.put(new IrisBlockVector(x, y, z), nearestBlockData(v, nearestBlocks, x, y, z)); - } else { - b.put(new IrisBlockVector(x, y, z), IrisObject.States.AIR); - } - } - } - } - - self.blocks = b; - self.surfaceSupportOffsets.reset(); - self.floatingFootprint.reset(); - } finally { - self.writeLock.unlock(); - } - } - - static void trihermite(IrisObject self, int rad) { - trihermite(self, rad, 0D, 0D); - } - - static void trihermite(IrisObject self, int rad, double tension, double bias) { - self.writeLock.lock(); - try { - VectorMap v = self.blocks; - VectorMap b = new VectorMap<>(); - IrisPosition min = self.getAABB().min(); - IrisPosition max = self.getAABB().max(); - NearestBlockIndex nearestBlocks = NearestBlockIndex.create(v); - - for (int x = min.getX(); x <= max.getX(); x++) { - for (int y = min.getY(); y <= max.getY(); y++) { - for (int z = min.getZ(); z <= max.getZ(); z++) { - if (Interpolation3D.getTrihermite(x, y, z, rad, (xx, yy, zz) -> { - PlatformBlockState data = v.get(new IrisBlockVector((int) xx, (int) yy, (int) zz)); - - if (B.isAir(data)) { - return 0; - } - - return 1; - }, tension, bias) >= 0.5) { - b.put(new IrisBlockVector(x, y, z), nearestBlockData(v, nearestBlocks, x, y, z)); - } else { - b.put(new IrisBlockVector(x, y, z), IrisObject.States.AIR); - } - } - } - } - - self.blocks = b; - self.surfaceSupportOffsets.reset(); - self.floatingFootprint.reset(); - } finally { - self.writeLock.unlock(); - } - } - - private static PlatformBlockState nearestBlockData(VectorMap blocks, - NearestBlockIndex nearestBlocks, - int x, int y, int z) { - IrisBlockVector vv = new IrisBlockVector(x, y, z); - PlatformBlockState direct = blocks.get(vv); - if (!B.isAir(direct)) { - return direct; - } - return nearestBlocks.nearest(x, y, z, direct); - } - - static final class NearestBlockIndex { - private static final Comparator X_ORDER = Comparator - .comparingInt(NearestBlock::x) - .thenComparingInt(NearestBlock::rank); - private static final Comparator Y_ORDER = Comparator - .comparingInt(NearestBlock::y) - .thenComparingInt(NearestBlock::rank); - private static final Comparator Z_ORDER = Comparator - .comparingInt(NearestBlock::z) - .thenComparingInt(NearestBlock::rank); - - private final NearestNode root; - private PlatformBlockState bestState; - private double bestDistance; - private int bestRank; - - private NearestBlockIndex(NearestNode root) { - this.root = root; - } - - static NearestBlockIndex create(VectorMap blocks) { - List points = new ArrayList<>(blocks.size()); - VectorMap.Cursor cursor = blocks.cursor(); - int rank = 0; - while (cursor.next()) { - PlatformBlockState state = cursor.value(); - if (!B.isAir(state)) { - IrisBlockVector position = cursor.key(); - points.add(new NearestBlock(position.getBlockX(), position.getBlockY(), position.getBlockZ(), - rank, state)); - } - rank++; - } - - NearestBlock[] pointArray = points.toArray(new NearestBlock[0]); - return new NearestBlockIndex(build(pointArray, 0, pointArray.length, 0)); - } - - PlatformBlockState nearest(int x, int y, int z, PlatformBlockState fallback) { - if (root == null) { - return fallback; - } - - bestState = fallback; - bestDistance = Double.MAX_VALUE; - bestRank = Integer.MAX_VALUE; - search(root, x, y, z); - return bestState; - } - - private static NearestNode build(NearestBlock[] points, int from, int to, int depth) { - if (from >= to) { - return null; - } - - int axis = depth % 3; - Arrays.sort(points, from, to, comparator(axis)); - int middle = (from + to) >>> 1; - return new NearestNode( - points[middle], - axis, - build(points, from, middle, depth + 1), - build(points, middle + 1, to, depth + 1) - ); - } - - private static Comparator comparator(int axis) { - return switch (axis) { - case 0 -> X_ORDER; - case 1 -> Y_ORDER; - default -> Z_ORDER; - }; - } - - private void search(NearestNode node, int x, int y, int z) { - if (node == null) { - return; - } - - NearestBlock point = node.point(); - double xDistance = point.x() - x; - double yDistance = point.y() - y; - double zDistance = point.z() - z; - double distance = (xDistance * xDistance) + (yDistance * yDistance) + (zDistance * zDistance); - if (distance < bestDistance || (distance == bestDistance && point.rank() < bestRank)) { - bestState = point.state(); - bestDistance = distance; - bestRank = point.rank(); - } - - double axisDistance = switch (node.axis()) { - case 0 -> x - point.x(); - case 1 -> y - point.y(); - default -> z - point.z(); - }; - NearestNode near = axisDistance <= 0D ? node.lower() : node.upper(); - NearestNode far = axisDistance <= 0D ? node.upper() : node.lower(); - search(near, x, y, z); - if ((axisDistance * axisDistance) <= bestDistance) { - search(far, x, y, z); - } - } - } - - private record NearestNode(NearestBlock point, int axis, NearestNode lower, NearestNode upper) { - } - - private record NearestBlock(int x, int y, int z, int rank, PlatformBlockState state) { - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectTranslate.java b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectTranslate.java deleted file mode 100644 index a479e5d3b..000000000 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectTranslate.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.prefab; - -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.math.IrisBlockVector; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("object-translator") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Translate objects") -@Data -public class IrisObjectTranslate { - @MinNumber(-128) - @MaxNumber(128) - @Desc("The x shift in blocks") - private int x = 0; - - @Required - @MinNumber(-128) - @MaxNumber(128) - @Desc("The y shift in blocks") - private int y = 0; - - @MinNumber(-128) - @MaxNumber(128) - @Desc("Adds an additional amount of height randomly (translateY + rand(0 - yRandom))") - private int yRandom = 0; - - @MinNumber(-128) - @MaxNumber(128) - @Desc("The z shift in blocks") - private int z = 0; - - public boolean canTranslate() { - return x != 0 || y != 0 || z != 0; - } - - public IrisBlockVector translate(IrisBlockVector i) { - if (canTranslate()) { - return (IrisBlockVector) i.clone().add(new IrisBlockVector(x, y, z)); - } - - return i; - } - - public IrisBlockVector translate(IrisBlockVector clone, IrisObjectRotation rotation, int sx, int sy, int sz) { - if (canTranslate()) { - return (IrisBlockVector) clone.clone().add(rotation.rotate(new IrisBlockVector(x, y, z), sx, sy, sz)); - } - - return clone; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/prefab/LegacyTileData.java b/src/main/java/art/arcane/iris/engine/object/prefab/LegacyTileData.java deleted file mode 100644 index d69ea1cab..000000000 --- a/src/main/java/art/arcane/iris/engine/object/prefab/LegacyTileData.java +++ /dev/null @@ -1,476 +0,0 @@ -package art.arcane.iris.engine.object.prefab; - -import org.bukkit.Bukkit; -import org.bukkit.DyeColor; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.Registry; -import org.bukkit.Tag; -import org.bukkit.block.Banner; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.block.CreatureSpawner; -import org.bukkit.block.Sign; -import art.arcane.iris.core.nms.container.Pair; -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.collection.KMap; -import art.arcane.iris.util.common.reflect.KeyedType; -import art.arcane.iris.util.common.scheduling.J; -import lombok.AllArgsConstructor; -import lombok.EqualsAndHashCode; -import lombok.NonNull; -import lombok.ToString; -import org.apache.commons.io.function.IOFunction; -import org.bukkit.block.banner.Pattern; -import org.bukkit.block.banner.PatternType; -import org.bukkit.block.sign.Side; -import org.bukkit.block.sign.SignSide; -import org.bukkit.block.data.BlockData; -import org.bukkit.entity.EntityType; -import org.bukkit.loot.LootTable; -import org.bukkit.loot.Lootable; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.StreamSupport; - -/** - * Bukkit-only pre-key tile format. Unreachable from the modded loaders: every entry point is - * either Bukkit-typed ({@link #fromBukkit(BlockState)}, reached only from - * {@link TileData#getTileState(Block, boolean)} and the Bukkit structure importer) or follows the - * bound platform-reader path in {@link TileData#read(DataInputStream)}, which returns before this - * class is ever referenced. The nested handler types - * therefore keep their raw Bukkit fields. - */ -@ToString -@EqualsAndHashCode(callSuper = false) -public class LegacyTileData extends TileData { - private final int id; - private final Handler handler; - - public LegacyTileData(DataInputStream in) throws IOException { - id = in.readShort(); - Pair> factory = Handlers.LEGACY.get(id); - if (factory == null) - throw new IOException("Unknown tile type: " + id); - handler = factory.getB().apply(in); - } - - private LegacyTileData(int id, Handler handler) { - this.id = id; - this.handler = handler; - } - - @Nullable - public static LegacyTileData fromBukkit(@NonNull BlockState tileState) { - Material type = tileState.getType(); - for (Integer id : Handlers.LEGACY.keySet()) { - Pair> factory = Handlers.LEGACY.get(id); - Handler handler = factory.getA().apply(tileState, type); - if (handler != null) - return new LegacyTileData(id, handler); - } - return null; - } - - private static final class Handlers { - private static final Map>> LEGACY = Map.of( - 0, new Pair<>(SignHandler::fromBukkit, SignHandler::new), - 1, new Pair<>(SpawnerHandler::fromBukkit, SpawnerHandler::new), - 2, new Pair<>(BannerHandler::fromBukkit, BannerHandler::new), - 3, new Pair<>(LootableHandler::fromBukkit, LootableHandler::new)); - } - - @Override - public @NonNull KMap getProperties() { - return new KMap<>(); - } - - @Override - public @NonNull String getMaterialKey() { - return TileData.materialKey(handler.getMaterial()); - } - - @Override - public Material resolveMaterial() { - return handler.getMaterial(); - } - - @Override - public boolean isApplicable(BlockData data) { - return handler.isApplicable(data); - } - - @Override - public void toBukkit(Block block) { - if (!J.runAt(block.getLocation(), () -> handler.toBukkit(block))) { - J.s(() -> handler.toBukkit(block)); - } - } - - @Override - public void toBinary(DataOutputStream out) throws IOException { - out.writeShort(id); - handler.toBinary(out); - } - - @Override - public TileData clone() { - return this; - } - - private interface Handler { - Material getMaterial(); - boolean isApplicable(BlockData data); - void toBinary(DataOutputStream out) throws IOException; - void toBukkit(Block block); - } - - @FunctionalInterface - private interface Builder { - @Nullable Handler apply(@NonNull BlockState blockState, @NonNull Material type); - } - - @ToString - @EqualsAndHashCode - @AllArgsConstructor - private static class SignHandler implements Handler { - private final String line1; - private final String line2; - private final String line3; - private final String line4; - private final DyeColor dyeColor; - - private SignHandler(DataInputStream in) throws IOException { - line1 = in.readUTF(); - line2 = in.readUTF(); - line3 = in.readUTF(); - line4 = in.readUTF(); - dyeColor = DyeColor.values()[in.readByte()]; - } - - private static SignHandler fromBukkit(BlockState blockState, Material type) { - if (!signsTag().isTagged(type) || !(blockState instanceof Sign sign)) - return null; - SignSide front = sign.getSide(Side.FRONT); - return new SignHandler(front.getLine(0), front.getLine(1), front.getLine(2), front.getLine(3), front.getColor()); - } - - @Override - public Material getMaterial() { - return Material.OAK_SIGN; - } - - @Override - public boolean isApplicable(BlockData data) { - return signsTag().isTagged(data.getMaterial()); - } - - @Override - public void toBinary(DataOutputStream out) throws IOException { - out.writeUTF(line1); - out.writeUTF(line2); - out.writeUTF(line3); - out.writeUTF(line4); - out.writeByte(dyeColor.ordinal()); - } - - @Override - public void toBukkit(Block block) { - Sign sign = (Sign) block.getState(); - SignSide front = sign.getSide(Side.FRONT); - SignSide back = sign.getSide(Side.BACK); - front.setLine(0, line1); - front.setLine(1, line2); - front.setLine(2, line3); - front.setLine(3, line4); - front.setColor(dyeColor); - back.setLine(0, line1); - back.setLine(1, line2); - back.setLine(2, line3); - back.setLine(3, line4); - back.setColor(dyeColor); - sign.update(); - } - } - @ToString - @EqualsAndHashCode - @AllArgsConstructor - private static class SpawnerHandler implements Handler { - private final EntityType type; - - private SpawnerHandler(DataInputStream in) throws IOException { - EntityType resolved = null; - if (in.markSupported()) { - in.mark(Integer.MAX_VALUE); - } - - try { - String keyString = in.readUTF(); - NamespacedKey key = NamespacedKey.fromString(keyString); - resolved = key == null ? null : Registry.ENTITY_TYPE.get(key); - if (resolved == null && in.markSupported()) { - in.reset(); - } - } catch (Throwable ignored) { - if (in.markSupported()) { - in.reset(); - } - } - - if (resolved == null) { - short legacyOrdinal = in.readShort(); - EntityType[] legacyValues = EntityType.values(); - if (legacyOrdinal >= 0 && legacyOrdinal < legacyValues.length) { - resolved = legacyValues[legacyOrdinal]; - } - } - - type = resolved == null ? EntityType.PIG : resolved; - } - - private static SpawnerHandler fromBukkit(BlockState blockState, Material material) { - if (material != Material.SPAWNER || !(blockState instanceof CreatureSpawner spawner)) - return null; - return new SpawnerHandler(spawner.getSpawnedType()); - } - - @Override - public Material getMaterial() { - return Material.SPAWNER; - } - - @Override - public boolean isApplicable(BlockData data) { - return data.getMaterial() == Material.SPAWNER; - } - - @Override - public void toBinary(DataOutputStream out) throws IOException { - NamespacedKey key = KeyedType.getKey(type); - out.writeUTF(key == null ? type.name() : key.toString()); - } - - @Override - public void toBukkit(Block block) { - CreatureSpawner spawner = (CreatureSpawner) block.getState(); - spawner.setSpawnedType(type); - spawner.update(); - } - } - @ToString - @EqualsAndHashCode - @AllArgsConstructor - private static class BannerHandler implements Handler { - private final KList patterns; - private final DyeColor baseColor; - - private BannerHandler(DataInputStream in) throws IOException { - DyeColor[] dyeColors = DyeColor.values(); - int baseColorIndex = in.readUnsignedByte(); - baseColor = baseColorIndex >= 0 && baseColorIndex < dyeColors.length ? dyeColors[baseColorIndex] : DyeColor.WHITE; - patterns = new KList<>(); - int listSize = in.readUnsignedByte(); - - if (in.markSupported()) { - in.mark(Integer.MAX_VALUE); - } - - boolean parsedKeyed = false; - try { - KList keyedPatterns = new KList<>(); - for (int i = 0; i < listSize; i++) { - int colorIndex = in.readUnsignedByte(); - DyeColor color = colorIndex >= 0 && colorIndex < dyeColors.length ? dyeColors[colorIndex] : DyeColor.WHITE; - NamespacedKey patternKey = NamespacedKey.fromString(in.readUTF()); - PatternType pattern = patternKey == null ? null : Registry.BANNER_PATTERN.get(patternKey); - if (pattern == null) { - throw new IOException("Unknown banner pattern key"); - } - keyedPatterns.add(new Pattern(color, pattern)); - } - patterns.addAll(keyedPatterns); - parsedKeyed = true; - } catch (Throwable ignored) { - if (in.markSupported()) { - in.reset(); - } - } - - if (parsedKeyed) { - return; - } - - PatternType[] legacyPatternTypes = PatternType.values(); - PatternType fallbackPattern = Registry.BANNER_PATTERN.get(NamespacedKey.minecraft("base")); - if (fallbackPattern == null && legacyPatternTypes.length > 0) { - fallbackPattern = legacyPatternTypes[0]; - } - - for (int i = 0; i < listSize; i++) { - int colorIndex = in.readUnsignedByte(); - DyeColor color = colorIndex >= 0 && colorIndex < dyeColors.length ? dyeColors[colorIndex] : DyeColor.WHITE; - int legacyPatternIndex = in.readUnsignedByte(); - PatternType pattern = legacyPatternIndex >= 0 && legacyPatternIndex < legacyPatternTypes.length ? legacyPatternTypes[legacyPatternIndex] : fallbackPattern; - if (pattern != null) { - patterns.add(new Pattern(color, pattern)); - } - } - } - - private static BannerHandler fromBukkit(BlockState blockState, Material type) { - if (!Tag.BANNERS.isTagged(type) || !(blockState instanceof Banner banner)) - return null; - return new BannerHandler(new KList<>(banner.getPatterns()), banner.getBaseColor()); - } - - @Override - public Material getMaterial() { - return Material.WHITE_BANNER; - } - - @Override - public boolean isApplicable(BlockData data) { - return Tag.BANNERS.isTagged(data.getMaterial()); - } - - @Override - public void toBinary(DataOutputStream out) throws IOException { - out.writeByte(baseColor.ordinal()); - out.writeByte(patterns.size()); - for (Pattern i : patterns) { - out.writeByte(i.getColor().ordinal()); - NamespacedKey key = KeyedType.getKey(i.getPattern()); - if (key == null) { - key = NamespacedKey.minecraft("base"); - } - out.writeUTF(key.toString()); - } - } - - @Override - public void toBukkit(Block block) { - Banner banner = (Banner) block.getState(); - banner.setBaseColor(baseColor); - banner.setPatterns(patterns); - banner.update(); - } - } - - @ToString - @EqualsAndHashCode - @AllArgsConstructor - private static class LootableHandler implements Handler { - private final Material material; - private final NamespacedKey lootTable; - private final long seed; - - private LootableHandler(DataInputStream in) throws IOException { - String materialKey = in.readUTF(); - NamespacedKey resolvedMaterial = NamespacedKey.fromString(materialKey); - Material resolved = resolvedMaterial == null ? null : Registry.MATERIAL.get(resolvedMaterial); - if (resolved == null) { - resolved = Material.matchMaterial(materialKey); - } - material = resolved == null ? Material.CHEST : resolved; - String tableKey = in.readUTF(); - lootTable = tableKey.isEmpty() ? null : NamespacedKey.fromString(tableKey); - seed = in.readLong(); - } - - private static LootableHandler fromBukkit(BlockState blockState, Material type) { - if (!(blockState instanceof Lootable lootable)) { - return null; - } - LootTable table = lootable.getLootTable(); - if (table == null) { - return null; - } - NamespacedKey key = table.getKey(); - if (key == null) { - return null; - } - return new LootableHandler(type, key, lootable.getSeed()); - } - - @Override - public Material getMaterial() { - return material; - } - - @Override - public boolean isApplicable(BlockData data) { - return data.getMaterial() == material; - } - - @Override - public void toBinary(DataOutputStream out) throws IOException { - NamespacedKey key = KeyedType.getKey(material); - out.writeUTF(key == null ? material.name() : key.toString()); - out.writeUTF(lootTable == null ? "" : lootTable.toString()); - out.writeLong(seed); - } - - @Override - public void toBukkit(Block block) { - if (lootTable == null || !(block.getState() instanceof Lootable lootable)) { - return; - } - LootTable table = Bukkit.getLootTable(lootTable); - if (table == null) { - return; - } - lootable.setLootTable(table); - lootable.setSeed(seed); - ((BlockState) lootable).update(true, false); - } - } - - private static Tag signsTag() { - return SignTags.get(); - } - - private static final class SignTags { - private static final AtomicCache> SIGNS = new AtomicCache<>(); - - private static Tag get() { - return SIGNS.aquire(() -> { - Tag signs = Bukkit.getTag("blocks", NamespacedKey.minecraft("all_signs"), Material.class); - if (signs != null) - return signs; - return new Tag<>() { - @Override - public boolean isTagged(@NotNull Material item) { - NamespacedKey key = KeyedType.getKey(item); - if (key != null) { - return key.getKey().endsWith("_sign"); - } - return item.name().toLowerCase(Locale.ROOT).endsWith("_sign"); - } - - @NotNull - @Override - public Set getValues() { - return StreamSupport.stream(Registry.MATERIAL.spliterator(), false) - .filter(this::isTagged) - .collect(Collectors.toUnmodifiableSet()); - } - - @NotNull - @Override - public NamespacedKey getKey() { - return NamespacedKey.minecraft("all_signs"); - } - }; - }); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/prefab/TileData.java b/src/main/java/art/arcane/iris/engine/object/prefab/TileData.java deleted file mode 100644 index 44e7c82c7..000000000 --- a/src/main/java/art/arcane/iris/engine/object/prefab/TileData.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.prefab; - -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.PlatformBlockState; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.Strictness; -import art.arcane.iris.platform.bukkit.BukkitPlatform; -import art.arcane.iris.util.common.reflect.KeyedType; -import art.arcane.volmlib.util.collection.KMap; -import lombok.AccessLevel; -import lombok.AllArgsConstructor; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.NonNull; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.block.Block; -import org.bukkit.block.TileState; -import org.bukkit.block.data.BlockData; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; - -@SuppressWarnings("ALL") -@Getter -@EqualsAndHashCode -@AllArgsConstructor -@NoArgsConstructor(access = AccessLevel.PROTECTED) -public class TileData implements Cloneable { - private static final Gson gson = new GsonBuilder().disableHtmlEscaping().setStrictness(Strictness.LENIENT).setObjectToNumberStrategy(com.google.gson.ToNumberPolicy.LONG_OR_DOUBLE).create(); - /** - * Memoized {@link #resolveMaterial()}. Pasting one tile resolves its material at least twice - * ({@link #isApplicable(BlockData)} then {@link #toBukkit(Block)}), and matchMaterial normalizes the string and - * then hits the Bukkit registry - an object with thousands of tiles paid for that thousands of times. - *

- * Static and keyed by the stored key rather than an instance field for two reasons: distinct tiles overwhelmingly - * repeat a handful of keys, so the cache is far more effective shared; and an instance field of a Bukkit type - - * transient or not - fails the pack purity gate, because {@code Class#getDeclaredFields()} resolves every declared - * field type eagerly, so one such field makes this class unloadable on Fabric/Forge/NeoForge. Static fields are - * never part of that walk. Bounded by the number of distinct material keys a pack can name. - */ - private static final Map RESOLVED_MATERIALS = new ConcurrentHashMap<>(); - private static volatile TileReader PLATFORM_READER = null; - private static volatile TileFactory PLATFORM_FACTORY = null; - - public interface TileReader { - TileData read(DataInputStream in) throws IOException; - } - - public interface TileFactory { - TileData create(PlatformBlockState state, KMap properties); - } - - public static synchronized TileReader bindPlatformReader(TileReader reader) { - TileReader previous = PLATFORM_READER; - PLATFORM_READER = Objects.requireNonNull(reader, "reader"); - return previous; - } - - public static synchronized TileFactory bindPlatformFactory(TileFactory factory) { - TileFactory previous = PLATFORM_FACTORY; - PLATFORM_FACTORY = Objects.requireNonNull(factory, "factory"); - return previous; - } - - public static synchronized void restorePlatformReader(TileReader reader) { - PLATFORM_READER = reader; - } - - public static synchronized void restorePlatformFactory(TileFactory factory) { - PLATFORM_FACTORY = factory; - } - - /** - * The block key this tile belongs to, stored as text so the field type never drags - * org.bukkit.Material onto a Gson field walk or into generated equals/hashCode/toString. - *

- * Gson data-compat: Material serialized as its enum name, so the same JSON member name with a - * String type parses every existing pack byte-for-byte. Persisted values are either a legacy - * uppercase enum name ("CHEST") or a namespaced key ("minecraft:chest"); both are accepted at - * the Bukkit resolution edge in {@link #resolveMaterial()}. - */ - @Getter(AccessLevel.NONE) - @NonNull - private String material; - @NonNull - private KMap properties; - - /** - * The platform-neutral block key. Safe on every platform - use this instead of resolving a - * Material anywhere outside the Bukkit adapter. - */ - public String getMaterialKey() { - return material; - } - - public static boolean setTileState(Block block, TileData data) { - if (block.getState() instanceof TileState && data.isApplicable(block.getBlockData())) - return data.toBukkitTry(block); - return false; - } - - public static TileData getTileState(Block block, boolean useLegacy) { - if (!BukkitPlatform.hasTile(block.getType())) - return null; - if (useLegacy) { - LegacyTileData legacy = LegacyTileData.fromBukkit(block.getState()); - if (legacy != null) - return legacy; - } - - return new TileData().fromBukkit(block); - } - - public static TileData of(PlatformBlockState state, KMap properties) { - TileFactory factory = PLATFORM_FACTORY; - if (factory != null) { - return factory.create(state, properties); - } - Object handle = state.nativeHandle(); - if (!(handle instanceof BlockData blockData)) { - return null; - } - return new TileData(materialKey(blockData.getMaterial()), properties); - } - - public static TileData read(DataInputStream in) throws IOException { - TileReader reader = PLATFORM_READER; - if (reader != null) { - return reader.read(in); - } - if (!in.markSupported()) - throw new IOException("Mark not supported"); - in.mark(Integer.MAX_VALUE); - try { - // Resolving the material is the modern/legacy stream discriminator: an unresolvable - // first UTF means these bytes are a LegacyTileData record, not a modern one. - Material resolved = Material.matchMaterial(in.readUTF()); - if (resolved == null) - throw new IOException("Not a modern tile record"); - return new TileData(materialKey(resolved), gson.fromJson(in.readUTF(), KMap.class)); - } catch (Throwable e) { - in.reset(); - return new LegacyTileData(in); - } finally { - in.mark(0); - } - } - - /** - * Bukkit resolution edge: canonicalizes a Material to the namespaced key form that - * {@link #toBinary(DataOutputStream)} has always written, falling back to the enum name. - */ - static String materialKey(Material material) { - if (material == null) { - return ""; - } - NamespacedKey key = KeyedType.getKey(material); - return key == null ? material.name() : key.toString(); - } - - /** - * Bukkit resolution edge. Accepts both persisted forms: the legacy uppercase enum name - * ("CHEST") and the namespaced key ("minecraft:chest") - matchMaterial handles both. - */ - public Material resolveMaterial() { - if (material == null || material.isEmpty()) { - return null; - } - - Material cached = RESOLVED_MATERIALS.get(material); - - if (cached != null) { - return cached; - } - - Material resolved = Material.matchMaterial(material); - - if (resolved != null) { - RESOLVED_MATERIALS.put(material, resolved); - } - - return resolved; - } - - public boolean isApplicable(BlockData data) { - Material resolved = resolveMaterial(); - return resolved != null && data.getMaterial() == resolved; - } - - public void toBukkit(Block block) { - Material resolved = resolveMaterial(); - if (resolved == null) throw new IllegalStateException("Material not set: " + material); - if (block.getType() != resolved) - throw new IllegalStateException("Material mismatch: " + block.getType() + " vs " + resolved); - BukkitPlatform.deserializeTile(properties, block.getLocation()); - } - - public TileData fromBukkit(Block block) { - if (material != null && !material.isEmpty()) { - Material resolved = resolveMaterial(); - if (block.getType() != resolved) - throw new IllegalStateException("Material mismatch: " + block.getType() + " vs " + material); - } else { - material = materialKey(block.getType()); - } - properties = BukkitPlatform.serializeTile(block.getLocation()); - return this; - } - - public boolean toBukkitTry(Block block) { - try { - //noinspection unchecked - toBukkit(block); - return true; - } catch (Throwable e) { - IrisLogging.reportError(e); - } - - return false; - } - - public boolean fromBukkitTry(Block block) { - try { - //noinspection unchecked - fromBukkit(block); - return true; - } catch (Throwable e) { - IrisLogging.reportError(e); - - } - - return false; - } - - public void toBinary(DataOutputStream out) throws IOException { - // The field already holds the canonical key form that this stream has always carried. - out.writeUTF(material == null ? "" : material); - out.writeUTF(gson.toJson(properties)); - } - - @Override - public TileData clone() { - TileData clone = new TileData(); - clone.material = material; - clone.properties = properties.copy(); //TODO make a deep copy - return clone; - } - - @Override - public String toString() { - return String.valueOf(material) + gson.toJson(properties); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/prefab/matter/IrisMatterObject.java b/src/main/java/art/arcane/iris/engine/object/prefab/matter/IrisMatterObject.java deleted file mode 100644 index bc50c7d52..000000000 --- a/src/main/java/art/arcane/iris/engine/object/prefab/matter/IrisMatterObject.java +++ /dev/null @@ -1,59 +0,0 @@ -package art.arcane.iris.engine.object.prefab.matter; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.util.project.matter.IrisMatterContext; -import art.arcane.iris.util.project.matter.IrisMatterSupport; -import art.arcane.volmlib.util.matter.IrisMatter; -import art.arcane.volmlib.util.matter.Matter; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.io.File; -import java.io.IOException; - -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisMatterObject extends IrisRegistrant { - private final Matter matter; - - public IrisMatterObject() { - this(1, 1, 1); - } - - public IrisMatterObject(int w, int h, int d) { - this(createMatter(w, h, d)); - } - - public IrisMatterObject(Matter matter) { - IrisMatterSupport.ensureRegistered(); - this.matter = matter; - } - - public static IrisMatterObject from(IrisObject object) { - return new IrisMatterObject(IrisMatterSupport.from(object)); - } - - public static IrisMatterObject from(File j, IrisData data) throws IOException { - IrisMatterSupport.ensureRegistered(); - try (IrisMatterContext.Scope scope = IrisMatterContext.open(data)) { - return new IrisMatterObject(Matter.read(j)); - } - } - - private static Matter createMatter(int w, int h, int d) { - IrisMatterSupport.ensureRegistered(); - return new IrisMatter(w, h, d); - } - - @Override - public String getFolderName() { - return "matter"; - } - - @Override - public String getTypeName() { - return "Matter"; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineStreamType.java b/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineStreamType.java deleted file mode 100644 index ba0d23fad..000000000 --- a/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineStreamType.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.runtime; - -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.util.project.stream.ProceduralStream; -import java.util.function.Function; - -@Desc("Represents a stream from the engine") -public enum IrisEngineStreamType { - @Desc("Represents the given slope at the x, z coordinates") - SLOPE((f) -> f.getComplex().getSlopeStream()), - - @Desc("Represents the base generator height at the given position. This includes only the biome generators / interpolation and noise features but does not include carving, caves.") - HEIGHT((f) -> f.getComplex().getHeightStream()), - - @Desc("Represents the base generator height at the given position. This includes only the biome generators / interpolation and noise features but does not include carving, caves. with Max(height, fluidHeight).") - HEIGHT_OR_FLUID((f) -> f.getComplex().getHeightFluidStream()), - - @Desc("Represents the overlay noise generators summed (dimension setting)") - OVERLAY_NOISE((f) -> f.getComplex().getOverlayStream()), - - @Desc("Represents the noise style of regions") - REGION_STYLE((f) -> f.getComplex().getRegionStyleStream()), - - @Desc("Represents the identity of regions. Each region has a unique number (very large numbers)") - REGION_IDENTITY((f) -> f.getComplex().getRegionIdentityStream()); - - private final Function> getter; - - IrisEngineStreamType(Function> getter) { - this.getter = getter; - } - - public ProceduralStream get(Engine engine) { - return getter.apply(engine); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineValueType.java b/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineValueType.java deleted file mode 100644 index f676276b1..000000000 --- a/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineValueType.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.runtime; - -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.annotations.Desc; - -import java.util.function.Function; - -@Desc("Represents a value from the engine") -public enum IrisEngineValueType { - @Desc("Represents actual height of the engine") - ENGINE_HEIGHT((f) -> Double.valueOf(f.getHeight())), - - @Desc("Represents virtual bottom of the engine in the compound. If this engine is on top of another engine, it's min height would be at the maxHeight of the previous engine + 1") - ENGINE_MIN_HEIGHT((f) -> Double.valueOf(f.getMinHeight())), - - @Desc("Represents virtual top of the engine in the compound. If this engine is below another engine, it's max height would be at the minHeight of the next engine - 1") - ENGINE_MAX_HEIGHT((f) -> Double.valueOf(f.getWorld().maxHeight())), - - @Desc("The fluid height defined in the dimension file") - FLUID_HEIGHT((f) -> Double.valueOf(f.getComplex().getFluidHeight())), - ; - - private final Function getter; - - IrisEngineValueType(Function getter) { - this.getter = getter; - } - - public Double get(Engine engine) { - return getter.apply(engine); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/runtime/StudioMode.java b/src/main/java/art/arcane/iris/engine/object/runtime/StudioMode.java deleted file mode 100644 index 034eb6572..000000000 --- a/src/main/java/art/arcane/iris/engine/object/runtime/StudioMode.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.runtime; - -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.platform.BukkitChunkGenerator; -import art.arcane.iris.engine.platform.studio.generators.BiomeBuffetGenerator; -import art.arcane.iris.engine.platform.studio.generators.ObjectStudioGenerator; - -@Desc("Represents a studio mode") -public enum StudioMode { - @Desc("Installs no studio generator; the dimension generates normally.") - NORMAL, - - @Desc("Debug layout: every biome in the dimension on a square grid, one chunk per biome cell, barrier floor past the last biome. Bukkit studio worlds only.") - BIOME_BUFFET_1x1, - - @Desc("Debug layout: every biome on a square grid with 3x3-chunk cells per biome, barrier floor past the last biome. Bukkit studio worlds only.") - BIOME_BUFFET_3x3, - - @Desc("Debug layout: every biome on a square grid with 5x5-chunk cells per biome, barrier floor past the last biome. Bukkit studio worlds only.") - BIOME_BUFFET_5x5, - - @Desc("Debug layout: every biome on a square grid with 9x9-chunk cells per biome, barrier floor past the last biome. Bukkit studio worlds only.") - BIOME_BUFFET_9x9, - - @Desc("Debug layout: every biome on a square grid with 18x18-chunk cells per biome, barrier floor past the last biome. Bukkit studio worlds only.") - BIOME_BUFFET_18x18, - - @Desc("Debug layout: every biome on a square grid with 36x36-chunk cells per biome, barrier floor past the last biome. Bukkit studio worlds only.") - BIOME_BUFFET_36x36, - - @Desc("Deprecated: generates exactly like NORMAL and will be removed in a future release.") - REGION_BUFFET, - - @Desc("Replaces terrain with the object studio: a flat polished-deepslate floor laying every pack object out on framed, end-rod-marked grid plinths. Bukkit studio worlds only.") - OBJECT_BUFFET; - - public void inject(BukkitChunkGenerator c) { - switch (this) { - case NORMAL, REGION_BUFFET -> c.setStudioGenerator(null); - case BIOME_BUFFET_1x1 -> c.setStudioGenerator(new BiomeBuffetGenerator(c.getEngine(), 1)); - case BIOME_BUFFET_3x3 -> c.setStudioGenerator(new BiomeBuffetGenerator(c.getEngine(), 3)); - case BIOME_BUFFET_5x5 -> c.setStudioGenerator(new BiomeBuffetGenerator(c.getEngine(), 5)); - case BIOME_BUFFET_9x9 -> c.setStudioGenerator(new BiomeBuffetGenerator(c.getEngine(), 9)); - case BIOME_BUFFET_18x18 -> c.setStudioGenerator(new BiomeBuffetGenerator(c.getEngine(), 18)); - case BIOME_BUFFET_36x36 -> c.setStudioGenerator(new BiomeBuffetGenerator(c.getEngine(), 36)); - case OBJECT_BUFFET -> c.setStudioGenerator(new ObjectStudioGenerator(c.getEngine())); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java deleted file mode 100644 index 9c14ab28b..000000000 --- a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.structure; - -import art.arcane.iris.builtin.anchor.PlaceTrait; -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.builtin.blocks.ObjectReplace; -import art.arcane.iris.builtin.loot.LootTable; -import art.arcane.iris.builtin.loot.ObjectLoot; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawCompatibility; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawMode; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcell; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.RegistryListVanillaStructure; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A jigsaw structure. Starting from a pool, the assembler places a start piece and recursively attaches more pieces through matching connectors until it reaches the max depth or size. Pieces are Iris objects, so they carry the full object placement and block-control feature set.") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisStructure extends IrisRegistrant { - @Required - @RegistryListResource(IrisJigsawPool.class) - @Desc("The pool the assembler draws the start piece from.") - private String startPool = ""; - - @MinNumber(1) - @MaxNumber(30) - @Desc("The maximum jigsaw recursion depth. Larger values allow larger structures (e.g. villages) at the cost of generation time.") - private int maxDepth = 7; - - @MinNumber(1) - @MaxNumber(32) - @Desc("The maximum radius of the structure in chunks from its start piece. Acts as a hard bound on assembly size and collision checks.") - private int maxSizeChunks = 8; - - @Desc("Assembly topology. SPATIAL_JIGSAW preserves the existing freeform connector graph; PLANAR_JIGSAW declares a cell-aligned planar graph.") - private IrisJigsawMode mode = IrisJigsawMode.SPATIAL_JIGSAW; - - @Desc("Target compatibility contract for this structure. IRIS_EXTENDED permits Iris-only metadata; VANILLA_PORTABLE requires a graph that can be represented by vanilla jigsaw resources.") - private IrisJigsawCompatibility compatibility = IrisJigsawCompatibility.IRIS_EXTENDED; - - @Desc("How unresolved optional connector branches affect assembly. FAIL_ASSEMBLY preserves strict Iris behavior; TERMINATE_BRANCH matches vanilla jigsaw branch termination.") - private IrisJigsawBranchFailurePolicy branchFailurePolicy = IrisJigsawBranchFailurePolicy.FAIL_ASSEMBLY; - - @Desc("Default Studio cell dimensions. Legacy planar structures use this value for every workcell when planarWorkcells is empty.") - private IrisPosition cellSize = new IrisPosition(15, 15, 15); - - @Desc("Optional author-facing name for the single spatial Jigsaw Studio workcell. Spatial is shown when this is blank.") - private String spatialWorkcellDisplayName = ""; - - @ArrayType(type = IrisJigsawWorkcell.class) - @Desc("The six persistent planar Studio workcells. Leave empty only for the legacy cellSize fallback.") - private KList planarWorkcells = new KList<>(); - - @ArrayType(type = IrisJigsawThemeSet.class, min = 1) - @Desc("Weighted themes available to an assembly. Leave empty for one implicit unthemed assembly path.") - private KList themeSets = new KList<>(); - - @Desc("Whether every open connector must close with a real terminal piece through a mandatory direct fallback.") - private boolean requireCaps = false; - - @Desc("The place mode used when stamping each piece object into the world.") - private ObjectPlaceMode placeMode = ObjectPlaceMode.STRUCTURE_PIECE; - - @ArrayType(min = 1, type = ObjectReplace.class) - @Desc("Find-and-replace block edits applied to every piece of this structure, using the exact same syntax as an object's 'edit'. For example, replace stone bricks with obsidian.") - private KList edit = new KList<>(); - - @ArrayType(type = String.class, min = 1) - @RegistryListResource(LootTable.class) - @Desc("Loot tables applied to containers placed by this structure's pieces.") - private KList loot = new KList<>(); - - @RegistryListVanillaStructure - @Desc("If this structure was generated by importing a vanilla or datapack structure, this is that structure's key (provenance). Empty for hand-authored structures.") - private String vanillaSource = ""; - - /** Whether the structure's pieces are stamped where the assembler put them, as a vanilla jigsaw places them. */ - public boolean stampsPiecesWhereAssembled() { - return placeMode != null && placeMode.placeMode().has(PlaceTrait.RAW_STAMP); - } - - public IrisJigsawMode resolvedMode() { - return mode == null ? IrisJigsawMode.SPATIAL_JIGSAW : mode; - } - - public IrisJigsawCompatibility resolvedCompatibility() { - return compatibility == null ? IrisJigsawCompatibility.IRIS_EXTENDED : compatibility; - } - - public IrisJigsawBranchFailurePolicy resolvedBranchFailurePolicy() { - return branchFailurePolicy == null - ? IrisJigsawBranchFailurePolicy.FAIL_ASSEMBLY - : branchFailurePolicy; - } - - public IrisObjectPlacement createLootPlacement(String objectKey) { - IrisObjectPlacement placement = new IrisObjectPlacement(); - placement.getPlace().add(objectKey); - placement.setOverrideGlobalLoot(false); - if (loot == null) { - return placement; - } - for (String lootTable : loot) { - if (lootTable != null && !lootTable.isBlank()) { - placement.getLoot().add(new ObjectLoot(lootTable, 1)); - } - } - return placement; - } - - @Override - public String getFolderName() { - return "structures"; - } - - @Override - public String getTypeName() { - return "Structure"; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConnector.java b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConnector.java deleted file mode 100644 index dc99b49cc..000000000 --- a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConnector.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.structure.jigsaw; - -import art.arcane.iris.engine.object.value.IrisDirection; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Required; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.util.Objects; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A jigsaw connection point on a piece. When two connectors face each other and their names match, the assembler may join the pieces.") -@Data -public class IrisJigsawConnector { - public static IrisPosition canonicalPlanarPosition(IrisPosition cellSize, IrisDirection direction) { - IrisPosition dimensions = Objects.requireNonNull(cellSize, "Planar jigsaw cell size"); - IrisDirection face = Objects.requireNonNull(direction, "Planar jigsaw connector direction"); - if (dimensions.getX() < 1 || dimensions.getY() < 1 || dimensions.getZ() < 1) { - throw new IllegalArgumentException("Planar jigsaw cell dimensions must be positive"); - } - int centerX = dimensions.getX() / 2; - int centerY = dimensions.getY() / 2; - int centerZ = dimensions.getZ() / 2; - return switch (face) { - case NORTH_NEGATIVE_Z -> new IrisPosition(centerX, centerY, 0); - case EAST_POSITIVE_X -> new IrisPosition(dimensions.getX() - 1, centerY, centerZ); - case SOUTH_POSITIVE_Z -> new IrisPosition(centerX, centerY, dimensions.getZ() - 1); - case WEST_NEGATIVE_X -> new IrisPosition(0, centerY, centerZ); - case UP_POSITIVE_Y, DOWN_NEGATIVE_Y -> throw new IllegalArgumentException( - "Planar jigsaw connector direction must be horizontal"); - }; - } - - @Required - @Desc("The position of this connector relative to the piece object's origin (0,0,0 is the lowest-corner of the object).") - private IrisPosition position = new IrisPosition(); - - @Required - @Desc("The direction this connector faces. The connecting piece is placed on this side.") - private IrisDirection direction = IrisDirection.NORTH_NEGATIVE_Z; - - @Required - @Desc("The connector's authored top direction, used to preserve aligned vanilla jigsaw orientation.") - private IrisDirection top = IrisDirection.UP_POSITIVE_Y; - - @Required - @RegistryListResource(IrisJigsawPool.class) - @Desc("The jigsaw pool to draw the connecting piece from.") - private String pool = ""; - - @Desc("The identity exposed by this connector. Another connector can attach when its targetName equals this name, matching Minecraft's jigsaw target-to-name contract.") - private String name = ""; - - @Desc("The name this connector wants to connect to on the other piece.") - private String targetName = ""; - - @Desc("Optional Iris-only connection channel. Matching is exact, case-sensitive, and whitespace-sensitive; empty channels match only other empty channels.") - private String channel = ""; - - @Desc("How the connecting piece may be rotated relative to this connector.") - private JigsawJoint joint = JigsawJoint.ROLLABLE; - - @Required - @Desc("Block state placed where this jigsaw marker was authored after assembly. Used when exporting or capturing Mojang-style jigsaw templates.") - private String finalState = "minecraft:air"; - - @Desc("Signed priority for selecting this connector within its piece. Higher values are processed before lower values; equal priorities preserve authored order.") - private int selectionPriority = 0; - - @Desc("Signed priority assigned to a child piece attached through this connector. Higher-priority child pieces expand first; equal priorities preserve attachment order.") - private int placementPriority = 0; -} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPiece.java b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPiece.java deleted file mode 100644 index 4e2c03202..000000000 --- a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPiece.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.structure.jigsaw; - -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A jigsaw piece. A piece is a single Iris object plus the connection points (connectors) that let the assembler attach other pieces to it.") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisJigsawPiece extends IrisRegistrant { - @Desc("Optional author-facing name shown by Jigsaw Studio. The resource key is shown when this is blank.") - private String displayName = ""; - - @Required - @RegistryListResource(IrisObject.class) - @Desc("The object (schematic) that makes up this piece.") - private String object = ""; - - @ArrayType(type = IrisJigsawConnector.class, min = 1) - @Desc("The jigsaw connection points on this piece.") - private KList connectors = new KList<>(); - - @Desc("If true, this piece may be rotated around the Y axis when placed so the assembler can match its connectors. Disable for pieces that must keep a fixed orientation.") - private boolean rotatable = true; - - @Desc("If true, this piece's object bounds block overlapping jigsaw pieces. Disable for connector-only scaffolds whose stored volume is intentionally shared with physical pieces.") - private boolean collidable = true; - - @ArrayType(type = String.class, min = 1) - @Desc("Theme keys that may select this piece. An empty list makes the piece available to every selected theme.") - private KList themes = new KList<>(); - - @Desc("Deterministic depth, placement-count, and terminal-role rules for this piece.") - private IrisJigsawPieceRules rules = new IrisJigsawPieceRules(); - - public boolean supportsTheme(String selectedTheme) { - if (themes == null || themes.isEmpty()) { - return true; - } - if (selectedTheme == null || selectedTheme.isBlank()) { - return false; - } - for (String theme : themes) { - if (selectedTheme.equals(theme)) { - return true; - } - } - return false; - } - - public IrisJigsawPieceRules resolvedRules() { - return rules == null ? new IrisJigsawPieceRules() : rules; - } - - @Override - public String getFolderName() { - return "jigsaw-pieces"; - } - - @Override - public String getTypeName() { - return "Jigsaw Piece"; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceEntry.java b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceEntry.java deleted file mode 100644 index c022d4de8..000000000 --- a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceEntry.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.structure.jigsaw; - -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A weighted reference to a jigsaw piece inside a jigsaw pool.") -@Data -public class IrisJigsawPieceEntry { - @RegistryListResource(IrisJigsawPiece.class) - @Desc("The jigsaw piece this entry refers to. Omit when empty is true.") - private String piece; - - @MinNumber(1) - @Desc("The relative weight of this piece within its pool. Higher weights are chosen more often.") - private int weight = 1; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The independent eligibility chance applied to this exact pool membership before weighted selection. Zero never passes and one always passes.") - private double chance = 1D; - - @Desc("When true, choosing this entry successfully terminates the current branch without placing a piece.") - private boolean empty = false; - - public IrisJigsawPieceEntry(String piece, int weight) { - this(piece, weight, 1D, false); - } - - public boolean requiresChanceRoll() { - return chance > 0D && chance < 1D; - } - - public boolean passesChance(double roll) { - if (!Double.isFinite(roll) || roll < 0D || roll >= 1D) { - throw new IllegalArgumentException("Jigsaw chance roll must be finite and within 0 inclusive and 1 exclusive"); - } - return chance >= 1D || chance > 0D && roll < chance; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPool.java b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPool.java deleted file mode 100644 index f20ae5e0d..000000000 --- a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPool.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.structure.jigsaw; - -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A jigsaw pool. A pool is a weighted set of pieces the assembler chooses from when a connector targets this pool.") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisJigsawPool extends IrisRegistrant { - @ArrayType(type = IrisJigsawPieceEntry.class, min = 1) - @Desc("The weighted pieces in this pool.") - private KList pieces = new KList<>(); - - @RegistryListResource(IrisJigsawPool.class) - @Desc("The direct fallback pool tried after this pool, or used alone at maximum depth. The fallback pool's own fallback is not part of the same selection. Leave empty to stop expanding at maximum depth.") - private String fallback = ""; - - @Desc("Whether failure to place from this pool must be resolved through its direct fallback even when the structure does not require every branch to be capped.") - private boolean mandatoryFallback = false; - - public boolean requiresFallback(boolean structureRequiresCaps) { - return structureRequiresCaps || mandatoryFallback; - } - - @Override - public String getFolderName() { - return "jigsaw-pools"; - } - - @Override - public String getTypeName() { - return "Jigsaw Pool"; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcell.java b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcell.java deleted file mode 100644 index e998e142e..000000000 --- a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcell.java +++ /dev/null @@ -1,40 +0,0 @@ -package art.arcane.iris.engine.object.structure.jigsaw; - -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Data -@Desc("Persistent authoring bounds and runtime availability for one planar jigsaw workcell.") -public class IrisJigsawWorkcell { - @Desc("Optional author-facing name shown by Jigsaw Studio. The canonical archetype name is shown when this is blank.") - private String displayName = ""; - - @Desc("The orientation-independent planar connector shape configured by this workcell.") - private IrisJigsawWorkcellArchetype archetype = IrisJigsawWorkcellArchetype.BLANK; - - @MinNumber(3) - @MaxNumber(128) - @Desc("The maximum canonical variant width that this workcell can contain, in blocks.") - private int width = 16; - - @MinNumber(1) - @MaxNumber(192) - @Desc("The maximum variant height that this workcell can contain, in blocks.") - private int height = 16; - - @MinNumber(3) - @MaxNumber(128) - @Desc("The maximum canonical variant depth that this workcell can contain, in blocks.") - private int depth = 16; - - @Desc("Whether pieces with this planar connector shape participate in assembly and vanilla export.") - private boolean enabled = true; -} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcellArchetype.java b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcellArchetype.java deleted file mode 100644 index 4275be726..000000000 --- a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcellArchetype.java +++ /dev/null @@ -1,88 +0,0 @@ -package art.arcane.iris.engine.object.structure.jigsaw; - -import art.arcane.iris.engine.object.annotations.Desc; - -@Desc("The orientation-independent connector shape represented by a planar jigsaw workcell.") -public enum IrisJigsawWorkcellArchetype { - @Desc("Pieces with no horizontal connectors: sealed filler cells that terminate nothing and are excluded from the default piece pool.") - BLANK(0), - - @Desc("One-connector dead-end pieces; the Studio bay seeds a single north connector and new projects mark these as terminal caps.") - END(1), - - @Desc("Two-connector pass-through pieces with openings on opposite sides; the Studio bay seeds north and south connectors.") - STRAIGHT(5), - - @Desc("Two-connector right-angle pieces with openings on adjacent sides; the Studio bay seeds north and east connectors.") - CORNER(3), - - @Desc("Three-connector junction pieces; the Studio bay seeds north, east, and west connectors.") - TEE(11), - - @Desc("Four-connector pieces open on all sides; new projects use this archetype as the structure's start piece.") - CROSS(15); - - private final int canonicalMask; - - IrisJigsawWorkcellArchetype(int canonicalMask) { - this.canonicalMask = canonicalMask; - } - - public static IrisJigsawWorkcellArchetype fromPiece(IrisJigsawPiece piece) { - if (piece == null || piece.getConnectors() == null) { - return BLANK; - } - return fromMask(horizontalMask(piece)); - } - - public static IrisJigsawWorkcellArchetype fromMask(int mask) { - if (mask < 0 || mask > 15) { - throw new IllegalArgumentException("Planar jigsaw topology mask must be between 0 and 15"); - } - int connections = Integer.bitCount(mask); - return switch (connections) { - case 0 -> BLANK; - case 1 -> END; - case 2 -> mask == 5 || mask == 10 ? STRAIGHT : CORNER; - case 3 -> TEE; - case 4 -> CROSS; - default -> throw new IllegalStateException("Unreachable planar jigsaw topology"); - }; - } - - public static int horizontalMask(IrisJigsawPiece piece) { - if (piece == null || piece.getConnectors() == null) { - return 0; - } - int mask = 0; - for (IrisJigsawConnector connector : piece.getConnectors()) { - if (connector == null || connector.getDirection() == null) { - continue; - } - mask |= switch (connector.getDirection()) { - case NORTH_NEGATIVE_Z -> 1; - case EAST_POSITIVE_X -> 2; - case SOUTH_POSITIVE_Z -> 4; - case WEST_NEGATIVE_X -> 8; - case UP_POSITIVE_Y, DOWN_NEGATIVE_Y -> 0; - }; - } - return mask; - } - - public int sourceToCanonicalQuarterTurns(IrisJigsawPiece piece) { - int sourceMask = horizontalMask(piece); - if (fromMask(sourceMask) != this) { - throw new IllegalArgumentException("Jigsaw piece does not match workcell archetype " + name()); - } - for (int quarterTurns = 0; quarterTurns < 4; quarterTurns++) { - int rotated = quarterTurns == 0 - ? sourceMask - : ((sourceMask << quarterTurns) | (sourceMask >>> (4 - quarterTurns))) & 15; - if (rotated == canonicalMask) { - return quarterTurns; - } - } - throw new IllegalStateException("No canonical rotation exists for planar jigsaw piece"); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/IrisGenerator.java b/src/main/java/art/arcane/iris/engine/object/terrain/IrisGenerator.java deleted file mode 100644 index 82668fe25..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/IrisGenerator.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.terrain; - -import art.arcane.iris.engine.object.noise.IrisInterpolator; -import art.arcane.iris.engine.object.noise.IrisNoiseGenerator; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.iris.util.project.interpolation.IrisInterpolation; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.util.project.noise.CellGenerator; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.util.List; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a composite generator of noise gens") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisGenerator extends IrisRegistrant { - private final transient AtomicCache cellGen = new AtomicCache<>(); - @MinNumber(0.001) - @Desc("The zoom or frequency.") - private double zoom = 1; - @MinNumber(0) - @Desc("The opacity, essentially a multiplier on the output.") - private double opacity = 1; - @Desc("Multiply the compsites instead of adding them") - private boolean multiplicitive = false; - @MinNumber(0.001) - @Desc("The size of the cell fractures") - private double cellFractureZoom = 1D; - @MinNumber(0) - @Desc("Cell Fracture Coordinate Shuffling") - private double cellFractureShuffle = 12D; - @Desc("The height of fracture cells. Set to 0 to disable") - private double cellFractureHeight = 0D; - @MinNumber(0) - @MaxNumber(1) - @Desc("How big are the cells (X,Z) relative to the veins that touch them. Between 0 and 1. 0.1 means thick veins, small cells.") - private double cellPercentSize = 0.75D; - @Desc("The offset to shift this noise x") - private double offsetX = 0; - @Desc("The offset to shift this noise z") - private double offsetZ = 0; - @Required - @Desc("The seed for this generator") - private long seed = 1; - @Required - @Desc("The interpolator to use when smoothing this generator into other regions & generators") - private IrisInterpolator interpolator = new IrisInterpolator(); - @MinNumber(0) - @MaxNumber(8192) - @Desc("Cliff Height Max. Disable with 0 for min and max") - private double cliffHeightMax = 0; - @MinNumber(0) - @MaxNumber(8192) - @Desc("Cliff Height Min. Disable with 0 for min and max") - private double cliffHeightMin = 0; - @ArrayType(min = 1, type = IrisNoiseGenerator.class) - @Desc("The list of noise gens this gen contains.") - private KList composite = new KList<>(); - @Desc("The noise gen for cliff height.") - private IrisNoiseGenerator cliffHeightGenerator = new IrisNoiseGenerator(); - - public double getMax() { - return opacity; - } - - public boolean hasCliffs() { - return cliffHeightMax > 0; - } - - public CellGenerator getCellGenerator(long seed) { - return cellGen.aquire(() -> new CellGenerator(new RNG(seed + 239466))); - } - - public T fit(T[] v, long superSeed, double rx, double rz) { - if (v.length == 0) { - return null; - } - - if (v.length == 1) { - return v[0]; - } - - return v[fit(0, v.length - 1, superSeed, rx, rz)]; - } - - public T fit(List v, long superSeed, double rx, double rz) { - if (v.size() == 0) { - return null; - } - - if (v.size() == 1) { - return v.get(0); - } - - return v.get(fit(0, v.size() - 1, superSeed, rx, rz)); - } - - public int fit(int min, int max, long superSeed, double rx, double rz) { - if (min == max) { - return min; - } - - double noise = getHeight(rx, rz, superSeed); - - return (int) Math.round(IrisInterpolation.lerp(min, max, noise)); - } - - public int fit(double min, double max, long superSeed, double rx, double rz) { - if (min == max) { - return (int) Math.round(min); - } - - double noise = getHeight(rx, rz, superSeed); - - return (int) Math.round(IrisInterpolation.lerp(min, max, noise)); - } - - public double fitDouble(double min, double max, long superSeed, double rx, double rz) { - if (min == max) { - return min; - } - - double noise = getHeight(rx, rz, superSeed); - - return IrisInterpolation.lerp(min, max, noise); - } - - public double getHeight(double rx, double rz, long superSeed) { - return getHeight(rx, 0, rz, superSeed, true); - } - - - public double getHeight(double rx, double ry, double rz, long superSeed) { - return getHeight(rx, ry, rz, superSeed, false); - } - - public double getHeight(double rx, double ry, double rz, long superSeed, boolean no3d) { - if (composite.isEmpty()) { - return 0; - } - - int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ); - double h = multiplicitive ? 1 : 0; - double tp = 0; - double sampleX = (rx + offsetX) / zoom; - double sampleZ = (rz + offsetZ) / zoom; - - if (composite.size() == 1) { - if (multiplicitive) { - h *= composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, getLoader()); - } else { - tp += composite.get(0).getOpacity(); - h += composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, getLoader()); - } - } else { - for (IrisNoiseGenerator i : composite) { - if (multiplicitive) { - h *= i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, getLoader()); - } else { - tp += i.getOpacity(); - h += i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, getLoader()); - } - } - } - - double v = multiplicitive ? h * opacity : (h / tp) * opacity; - - if (Double.isNaN(v)) { - v = 0; - } - - v = hasCliffs() ? cliff(rx, rz, v, superSeed + 294596 + hc) : v; - v = hasCellCracks() ? cell(rx, rz, v, superSeed + 48622 + hc) : v; - - return v; - } - - public double cell(double rx, double rz, double v, double superSeed) { - getCellGenerator(getSeed() + 46222).setShuffle(getCellFractureShuffle()); - double fractureX = rx / getCellFractureZoom(); - double fractureZ = rz / getCellFractureZoom(); - return getCellGenerator(getSeed() + 46222).getDistance(fractureX, fractureZ) > getCellPercentSize() ? (v * getCellFractureHeight()) : v; - } - - private boolean hasCellCracks() { - return getCellFractureHeight() != 0; - } - - public double getCliffHeight(double rx, double rz, double superSeed) { - int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ); - double sampleX = (rx + offsetX) / zoom; - double sampleZ = (rz + offsetZ) / zoom; - double h = cliffHeightGenerator.getNoise((long) (getSeed() + superSeed + hc), sampleX, sampleZ, getLoader()); - return IrisInterpolation.lerp(cliffHeightMin, cliffHeightMax, h); - } - - public double cliff(double rx, double rz, double v, double superSeed) { - double cliffHeight = getCliffHeight(rx, rz, superSeed - 34857); - return (Math.round((v * 255D) / cliffHeight) * cliffHeight) / 255D; - } - - public IrisGenerator rescale(double scale) { - zoom /= scale; - return this; - } - - public KList getAllComposites() { - KList g = new KList<>(); - - for (IrisNoiseGenerator i : composite) { - g.addAll(i.getAllComposites()); - } - - return g; - } - - @Override - public String getFolderName() { - return "generators"; - } - - @Override - public String getTypeName() { - return "Generator"; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/value/IRare.java b/src/main/java/art/arcane/iris/engine/object/value/IRare.java deleted file mode 100644 index 09cfcb19d..000000000 --- a/src/main/java/art/arcane/iris/engine/object/value/IRare.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.value; - -import art.arcane.volmlib.util.collection.KList; -import art.arcane.iris.util.project.stream.ProceduralStream; -import art.arcane.iris.util.project.stream.interpolation.Interpolated; -import java.util.List; - -public interface IRare { - static ProceduralStream stream(ProceduralStream noise, List possibilities) { - return ProceduralStream.of((x, z) -> pick(possibilities, noise.get(x, z)), - (x, y, z) -> pick(possibilities, noise.get(x, y, z)), - new Interpolated() { - @Override - public double toDouble(T t) { - return 0; - } - - @Override - public T fromDouble(double d) { - return null; - } - }); - } - - - static T pickSlowly(List possibilities, double noiseValue) { - if (possibilities.isEmpty()) { - return null; - } - - if (possibilities.size() == 1) { - return possibilities.get(0); - } - - KList rarityTypes = new KList<>(); - int totalRarity = 0; - for (T i : possibilities) { - totalRarity += IRare.get(i); - } - - for (T i : possibilities) { - rarityTypes.addMultiple(i, totalRarity / IRare.get(i)); - } - - return rarityTypes.get((int) (noiseValue * rarityTypes.last())); - } - - static T pick(List possibilities, double noiseValue) { - if (possibilities.isEmpty()) { - return null; - } - - if (possibilities.size() == 1) { - return possibilities.getFirst(); - } - - double total = 0; - for (T i : possibilities) { - total += 1d / IRare.get(i); - } - - double threshold = total * noiseValue; - double buffer = 0; - for (T i : possibilities) { - buffer += 1d / IRare.get(i); - if (buffer >= threshold) { - return i; - } - } - - return possibilities.getLast(); - } - - static int get(Object v) { - return v instanceof IRare ? Math.max(1, ((IRare) v).getRarity()) : 1; - } - - int getRarity(); -} diff --git a/src/main/java/art/arcane/iris/engine/object/value/IrisColor.java b/src/main/java/art/arcane/iris/engine/object/value/IrisColor.java deleted file mode 100644 index 33b8bfad2..000000000 --- a/src/main/java/art/arcane/iris/engine/object/value/IrisColor.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.value; - -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.spi.IrisLogging; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.awt.Color; - -@Snippet("color") -@Accessors(chain = true) -@NoArgsConstructor -@Desc("Represents a color") -@Data -public class IrisColor { - private final transient AtomicCache color = new AtomicCache<>(); - @MaxNumber(7) - @MinNumber(6) - @Desc("Pass in a 6 digit hexadecimal color to fill R G and B values. You can also include the # symbol, but it's not required.") - private String hex = null; - @MaxNumber(255) - @MinNumber(0) - @Desc("Represents the red channel. Only define this if you are not defining the hex value.") - private int red = 0; - @MaxNumber(255) - @MinNumber(0) - @Desc("Represents the green channel. Only define this if you are not defining the hex value.") - private int green = 0; - @MaxNumber(255) - @MinNumber(0) - @Desc("Represents the blue channel. Only define this if you are not defining the hex value.") - private int blue = 0; - - public static Color blend(Color... c) { - if (c == null || c.length <= 0) { - return null; - } - float ratio = 1f / ((float) c.length); - - int a = 0; - int r = 0; - int g = 0; - int b = 0; - - for (Color value : c) { - int rgb = value.getRGB(); - int a1 = (rgb >> 24 & 0xff); - int r1 = ((rgb & 0xff0000) >> 16); - int g1 = ((rgb & 0xff00) >> 8); - int b1 = (rgb & 0xff); - a += (a1 * ratio); - r += (r1 * ratio); - g += (g1 * ratio); - b += (b1 * ratio); - } - - return new Color(a << 24 | r << 16 | g << 8 | b); - } - - public Color getColor() { - return color.aquire(() -> { - if (hex != null) { - String v = (hex.startsWith("#") ? hex : "#" + hex).trim(); - try { - return Color.decode(v); - } catch (Throwable e) { - IrisLogging.reportError(e); - - } - } - - return new Color(red, green, blue); - }); - } - - public int getAsRGB() { - if (hex != null) { - try { - if (hex.startsWith("#")) hex = hex.substring(1); - return Integer.parseInt(hex, 16); - } catch (NumberFormatException e) { - return 0; - } - } - - return red << 16 | green << 8 | blue; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/value/IrisDirection.java b/src/main/java/art/arcane/iris/engine/object/value/IrisDirection.java deleted file mode 100644 index c386de231..000000000 --- a/src/main/java/art/arcane/iris/engine/object/value/IrisDirection.java +++ /dev/null @@ -1,392 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.value; - -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.volmlib.util.collection.GBiset; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.collection.KMap; -import art.arcane.volmlib.util.data.Cuboid.CuboidDirection; -import art.arcane.volmlib.util.math.DOP; -import art.arcane.volmlib.util.math.VectorMath; -import org.bukkit.Axis; -import org.bukkit.block.BlockFace; -import org.bukkit.util.Vector; - -import java.util.Map; - -/** - * Directions - * - * @author cyberpwn - */ -@Desc("A direction object") -public enum IrisDirection { - @Desc("0, 1, 0") - UP_POSITIVE_Y(0, 1, 0, CuboidDirection.Up), - @Desc("0, -1, 0") - DOWN_NEGATIVE_Y(0, -1, 0, CuboidDirection.Down), - @Desc("0, 0, -1") - NORTH_NEGATIVE_Z(0, 0, -1, CuboidDirection.North), - @Desc("0, 0, 1") - SOUTH_POSITIVE_Z(0, 0, 1, CuboidDirection.South), - @Desc("1, 0, 0") - EAST_POSITIVE_X(1, 0, 0, CuboidDirection.East), - @Desc("-1, 0, 0") - WEST_NEGATIVE_X(-1, 0, 0, CuboidDirection.West); - - private static KMap, DOP> permute = null; - - private final int x; - private final int y; - private final int z; - private final CuboidDirection f; - - IrisDirection(int x, int y, int z, CuboidDirection f) { - this.x = x; - this.y = y; - this.z = z; - this.f = f; - } - - public static IrisDirection getDirection(BlockFace f) { - return switch (f) { - case DOWN -> DOWN_NEGATIVE_Y; - case EAST, EAST_NORTH_EAST, EAST_SOUTH_EAST -> EAST_POSITIVE_X; - case NORTH, NORTH_NORTH_WEST, NORTH_EAST, NORTH_NORTH_EAST, NORTH_WEST -> NORTH_NEGATIVE_Z; - case SELF, UP -> UP_POSITIVE_Y; - case SOUTH, SOUTH_EAST, SOUTH_SOUTH_EAST, SOUTH_SOUTH_WEST, SOUTH_WEST -> SOUTH_POSITIVE_Z; - case WEST, WEST_NORTH_WEST, WEST_SOUTH_WEST -> WEST_NEGATIVE_X; - }; - - } - - public static IrisDirection closest(Vector v) { - double m = Double.MAX_VALUE; - IrisDirection s = null; - - for (IrisDirection i : values()) { - Vector x = i.toVector(); - double g = x.distance(v); - - if (g < m) { - m = g; - s = i; - } - } - - return s; - } - - public static IrisDirection closest(Vector v, IrisDirection... d) { - double m = Double.MAX_VALUE; - IrisDirection s = null; - - for (IrisDirection i : d) { - Vector x = i.toVector(); - double g = x.distance(v); - - if (g < m) { - m = g; - s = i; - } - } - - return s; - } - - public static IrisDirection closest(Vector v, KList d) { - double m = Double.MAX_VALUE; - IrisDirection s = null; - - for (IrisDirection i : d) { - Vector x = i.toVector(); - double g = x.distance(v); - - if (g < m) { - m = g; - s = i; - } - } - - return s; - } - - public static KList news() { - return new KList().add(NORTH_NEGATIVE_Z, EAST_POSITIVE_X, WEST_NEGATIVE_X, SOUTH_POSITIVE_Z); - } - - public static IrisDirection getDirection(Vector v) { - Vector k = VectorMath.triNormalize(v.clone().normalize()); - - for (IrisDirection i : udnews()) { - if (i.x == k.getBlockX() && i.y == k.getBlockY() && i.z == k.getBlockZ()) { - return i; - } - } - - return IrisDirection.NORTH_NEGATIVE_Z; - } - - public static KList udnews() { - return new KList().add(UP_POSITIVE_Y, DOWN_NEGATIVE_Y, NORTH_NEGATIVE_Z, EAST_POSITIVE_X, WEST_NEGATIVE_X, SOUTH_POSITIVE_Z); - } - - /** - * Get the directional value from the given byte from common directional blocks - * (MUST BE BETWEEN 0 and 5 INCLUSIVE) - * - * @param b the byte - * @return the direction or null if the byte is outside of the inclusive range - * 0-5 - */ - public static IrisDirection fromByte(byte b) { - if (b > 5 || b < 0) { - return null; - } - - if (b == 0) { - return DOWN_NEGATIVE_Y; - } else if (b == 1) { - return UP_POSITIVE_Y; - } else if (b == 2) { - return NORTH_NEGATIVE_Z; - } else if (b == 3) { - return SOUTH_POSITIVE_Z; - } else if (b == 4) { - return WEST_NEGATIVE_X; - } else { - return EAST_POSITIVE_X; - } - } - - public static void calculatePermutations() { - if (permute != null) { - return; - } - - permute = new KMap<>(); - - for (IrisDirection i : udnews()) { - for (IrisDirection j : udnews()) { - GBiset b = new GBiset<>(i, j); - - if (i.equals(j)) { - permute.put(b, new DOP("DIRECT") { - @Override - public Vector op(Vector v) { - return v; - } - }); - } else if (i.reverse().equals(j)) { - if (i.isVertical()) { - permute.put(b, new DOP("R180CCZ") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CCZ(VectorMath.rotate90CCZ(v)); - } - }); - } else { - permute.put(b, new DOP("R180CCY") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CCY(VectorMath.rotate90CCY(v)); - } - }); - } - } else if (getDirection(VectorMath.rotate90CX(i.toVector())).equals(j)) { - permute.put(b, new DOP("R90CX") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CX(v); - } - }); - } else if (getDirection(VectorMath.rotate90CCX(i.toVector())).equals(j)) { - permute.put(b, new DOP("R90CCX") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CCX(v); - } - }); - } else if (getDirection(VectorMath.rotate90CY(i.toVector())).equals(j)) { - permute.put(b, new DOP("R90CY") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CY(v); - } - }); - } else if (getDirection(VectorMath.rotate90CCY(i.toVector())).equals(j)) { - permute.put(b, new DOP("R90CCY") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CCY(v); - } - }); - } else if (getDirection(VectorMath.rotate90CZ(i.toVector())).equals(j)) { - permute.put(b, new DOP("R90CZ") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CZ(v); - } - }); - } else if (getDirection(VectorMath.rotate90CCZ(i.toVector())).equals(j)) { - permute.put(b, new DOP("R90CCZ") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CCZ(v); - } - }); - } else { - permute.put(b, new DOP("FAIL") { - @Override - public Vector op(Vector v) { - return v; - } - }); - } - } - } - } - - @Override - public String toString() { - return switch (this) { - case DOWN_NEGATIVE_Y -> "Down"; - case EAST_POSITIVE_X -> "East"; - case NORTH_NEGATIVE_Z -> "North"; - case SOUTH_POSITIVE_Z -> "South"; - case UP_POSITIVE_Y -> "Up"; - case WEST_NEGATIVE_X -> "West"; - }; - - } - - public boolean isVertical() { - return equals(DOWN_NEGATIVE_Y) || equals(UP_POSITIVE_Y); - } - - public Vector toVector() { - return new Vector(x, y, z); - } - - public boolean isCrooked(IrisDirection to) { - if (equals(to.reverse())) { - return false; - } - - return !equals(to); - } - - public Vector angle(Vector initial, IrisDirection d) { - calculatePermutations(); - - for (Map.Entry, DOP> entry : permute.entrySet()) { - GBiset i = entry.getKey(); - if (i.getA().equals(this) && i.getB().equals(d)) { - return entry.getValue().op(initial); - } - } - - return initial; - } - - public IrisDirection reverse() { - switch (this) { - case DOWN_NEGATIVE_Y: - return UP_POSITIVE_Y; - case EAST_POSITIVE_X: - return WEST_NEGATIVE_X; - case NORTH_NEGATIVE_Z: - return SOUTH_POSITIVE_Z; - case SOUTH_POSITIVE_Z: - return NORTH_NEGATIVE_Z; - case UP_POSITIVE_Y: - return DOWN_NEGATIVE_Y; - case WEST_NEGATIVE_X: - return EAST_POSITIVE_X; - default: - break; - } - - return EAST_POSITIVE_X; - } - - public int x() { - return x; - } - - public int y() { - return y; - } - - public int z() { - return z; - } - - public CuboidDirection f() { - return f; - } - - /** - * Get the byte value represented in some directional blocks - * - * @return the byte value - */ - public byte byteValue() { - switch (this) { - case DOWN_NEGATIVE_Y: - return 0; - case EAST_POSITIVE_X: - return 5; - case NORTH_NEGATIVE_Z: - return 2; - case SOUTH_POSITIVE_Z: - return 3; - case UP_POSITIVE_Y: - return 1; - case WEST_NEGATIVE_X: - return 4; - default: - break; - } - - return -1; - } - - public BlockFace getFace() { - return switch (this) { - case DOWN_NEGATIVE_Y -> BlockFace.DOWN; - case EAST_POSITIVE_X -> BlockFace.EAST; - case NORTH_NEGATIVE_Z -> BlockFace.NORTH; - case SOUTH_POSITIVE_Z -> BlockFace.SOUTH; - case UP_POSITIVE_Y -> BlockFace.UP; - case WEST_NEGATIVE_X -> BlockFace.WEST; - }; - - } - - public Axis getAxis() { - return switch (this) { - case DOWN_NEGATIVE_Y, UP_POSITIVE_Y -> Axis.Y; - case EAST_POSITIVE_X, WEST_NEGATIVE_X -> Axis.X; - case NORTH_NEGATIVE_Z, SOUTH_POSITIVE_Z -> Axis.Z; - }; - - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/IrisWorld.java b/src/main/java/art/arcane/iris/engine/object/world/IrisWorld.java deleted file mode 100644 index 625e6d15f..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/IrisWorld.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.world; - -import art.arcane.iris.spi.PlatformWorld; -import lombok.AccessLevel; -import lombok.Builder; -import lombok.Data; -import lombok.Getter; -import lombok.Setter; -import lombok.experimental.Accessors; - -import java.io.File; - -@Builder -@Data -@Accessors(chain = true, fluent = true) -public class IrisWorld { - private String platformIdentity; - private String name; - private File worldFolder; - - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private long seed; - private PlatformWorld platformWorld; - private int minHeight; - private int maxHeight; - - public long getRawWorldSeed() { - return seed; - } - - public String identity() { - return platformIdentity; - } - - public void setRawWorldSeed(long seed) { - this.seed = seed; - } - - public boolean hasPlatformWorld() { - return platformWorld != null; - } - - public int getHeight() { - return maxHeight - minHeight; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiome.java b/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiome.java deleted file mode 100644 index 587cd79c4..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiome.java +++ /dev/null @@ -1,422 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.world.biome; - -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.noise.NoiseStyle; -import art.arcane.iris.engine.object.value.IRare; -import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.framework.render.RenderType; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.engine.IrisComplex; -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.volmlib.util.cache.LazyBoundedCache; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.DependsOn; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListBiome; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.collection.KMap; -import art.arcane.volmlib.util.collection.KSet; -import art.arcane.iris.util.common.data.DataProvider; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.iris.util.project.context.IrisContext; -import lombok.AccessLevel; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.experimental.Accessors; -import art.arcane.iris.spi.PlatformBlockState; -import org.bukkit.block.Biome; - -import java.awt.Color; -import java.util.EnumMap; -import java.util.Objects; - -/** - * Represents a biome in a pack. This type is Gson deserialized straight out of user pack JSON, so - * the field block and the transient {@link AtomicCache} block below are load bearing and must not - * move. Behavior lives in the same-package companions: - * {@link IrisBiomeDerivatives}, - * {@link IrisBiomeColorRenderer} and {@link IrisBiomeGenLinks}. - */ -@Accessors(chain = true) -@NoArgsConstructor -@Desc("Represents a biome in iris. Biomes are placed inside of regions and hold objects.\nA biome consists of layers (block palletes), decorations, objects & generators.") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisBiome extends IrisRegistrant implements IRare { - private static final int BIOME_GENERATOR_CACHE_SIZE = 8; - - private final transient AtomicCache> genCache = new AtomicCache<>(); - private final transient AtomicCache> genCacheMax = new AtomicCache<>(); - private final transient AtomicCache> genCacheMin = new AtomicCache<>(); - private final transient AtomicCache cacheColor = new AtomicCache<>(); - private final transient AtomicCache cacheColorObjectDensity = new AtomicCache<>(); - private final transient AtomicCache cacheColorDecoratorLoad = new AtomicCache<>(); - private final transient AtomicCache cacheColorLayerLoad = new AtomicCache<>(); - private final transient AtomicCache cacheColorDepositLoad = new AtomicCache<>(); - private final transient AtomicCache childrenCell = new AtomicCache<>(); - @Getter(AccessLevel.NONE) - private final transient LazyBoundedCache biomeGenerators = - new LazyBoundedCache<>(BIOME_GENERATOR_CACHE_SIZE); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private transient volatile SeededBiomeGenerator recentBiomeGenerator; - private final transient AtomicCache> realChildren = new AtomicCache<>(); - private final transient AtomicCache derivativeResolved = new AtomicCache<>(); - private final transient AtomicCache vanillaDerivativeResolved = new AtomicCache<>(); - private final transient AtomicCache> biomeScatterResolved = new AtomicCache<>(); - private final transient AtomicCache> biomeSkyScatterResolved = new AtomicCache<>(); - @MinNumber(2) - @Required - @Desc("This is the human readable name for this biome. This can and should be different than the file name. This is not used for loading biomes in other objects.") - private String name = "Subterranean Land"; - @ArrayType(min = 1, type = IrisBiomeCustom.class) - @Desc("If the biome type custom is defined, specify this") - private KList customDerivitives; - @DependsOn({"biomeStyle", "biomeZoom", "biomeScatter"}) - @Desc("This changes the dispersion of the biome colors if multiple derivatives are chosen.") - private IrisGeneratorStyle biomeStyle = NoiseStyle.SIMPLEX.style(); - @MinNumber(1) - @MaxNumber(512) - @Desc("The rarity of this biome (integer)") - private int rarity = 1; - @Desc("A color for visualizing this biome with a color. I.e. #F13AF5. This will show up on the map.") - private String color = null; - @Required - @RegistryListBiome - @Desc("The raw derivative of this biome. This is required or the terrain will not properly generate. Use any vanilla biome type. Look in examples/biome-list.txt") - private String derivative = "minecraft:the_void"; - @Required - @RegistryListBiome - @Desc("Override the derivative used for vanilla structure selection. Iris still enforces the generated terrain role: land-only Minecraft derivatives on sea biomes expose no native structure biome, and land-only derivatives on shore biomes resolve as beach, while exact ocean, river, beach, and shore variants remain eligible. Non-Minecraft namespaces remain authoritative. Not defining this value selects derivative.") - private String vanillaDerivative = null; - @ArrayType(min = 1, type = String.class) - @RegistryListBiome - @Desc("You can instead specify multiple biome derivatives to randomly scatter colors in this biome") - private KList biomeScatter = new KList<>(); - @ArrayType(min = 1, type = String.class) - @RegistryListBiome - @Desc("Since 1.13 supports 3D biomes, you can add different derivative colors for anything above the terrain. (Think swampy tree leaves with a desert looking grass surface)") - private KList biomeSkyScatter = new KList<>(); - @DependsOn({"children"}) - @Desc("If this biome has children biomes, and the gen layer chooses one of this biomes children, how much smaller will it be (inside of this biome). Higher values means a smaller biome relative to this biome's size. Set higher than 1.0 and below 3.0 for best results.") - private double childShrinkFactor = 1.5; - @DependsOn({"children"}) - @Desc("If this biome has children biomes, and the gen layer chooses one of this biomes children, How will it be shaped?") - private IrisGeneratorStyle childStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - @RegistryListResource(IrisBiome.class) - @ArrayType(min = 1, type = String.class) - @Desc("List any biome names (file names without.json) here as children. Portions of this biome can sometimes morph into their children. Iris supports cyclic relationships such as A > B > A > B. Iris will stop checking 4 biomes down the tree.") - private KList children = new KList<>(); - @ArrayType(min = 1, type = IrisBiomeGeneratorLink.class) - @Desc("Generators for this biome. Multiple generators with different interpolation sizes will mix with other biomes how you would expect. This defines your biome height relative to the fluid height. Use negative for oceans.") - private KList generators = new KList().qadd(new IrisBiomeGeneratorLink()); - private transient volatile InferredType inferredType; - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient EnumMap inferredVariants = new EnumMap<>(InferredType.class); - - public synchronized IrisBiome setInferredType(InferredType inferredType) { - this.inferredType = inferredType; - return this; - } - - public IrisBiome withInferredType(InferredType type) { - Objects.requireNonNull(type, "type"); - // Lock-free fast path on the volatile field: this runs per column per implode level - // against biome instances shared by every burst thread. The variant map below stays - // monitor-guarded (plain EnumMap, not safe for concurrent reads during writes). - if (inferredType == type) { - return this; - } - return withInferredTypeSlow(type); - } - - private synchronized IrisBiome withInferredTypeSlow(InferredType type) { - if (inferredType == null) { - inferredType = type; - return this; - } - if (inferredType == type) { - return this; - } - IrisBiome cached = inferredVariants.get(type); - if (cached != null) { - return cached; - } - IrisData data = getLoader(); - if (data == null) { - throw new IllegalStateException("Cannot create an inferred biome variant without an Iris data loader."); - } - IrisBiome variant = data.getGson().fromJson(data.getGson().toJson(this), IrisBiome.class); - variant.setLoader(data); - variant.setLoadKey(getLoadKey()); - variant.setLoadFile(getLoadFile()); - variant.setModuleSettings(getModuleSettings()); - variant.inferredType = type; - inferredVariants.put(type, variant); - return variant; - } - - public Biome getDerivative() { - Biome cached = derivativeResolved.getIfPresent(); - - if (cached != null) { - return cached; - } - - return derivativeResolved.aquire(() -> IrisBiomeDerivatives.resolveBiomeKey(derivative)); - } - - public Biome getVanillaDerivative() { - Biome resolved = vanillaDerivative == null - ? null - : vanillaDerivativeResolved.aquire(() -> IrisBiomeDerivatives.resolveBiomeKey(vanillaDerivative)); - return resolved == null ? getDerivative() : resolved; - } - - public String getVanillaDerivativeKey() { - return IrisBiomeDerivatives.getVanillaDerivativeKey(derivative, vanillaDerivative); - } - - public String getStructureDerivativeKey() { - return IrisBiomeDerivatives.getStructureDerivativeKey(this); - } - - public String getDerivativeKey() { - return IrisBiomeDerivatives.namespacedBiomeKey(derivative); - } - - KList getBiomeScatterResolved() { - KList cached = biomeScatterResolved.getIfPresent(); - - if (cached != null) { - return cached; - } - - return biomeScatterResolved.aquire(() -> IrisBiomeDerivatives.resolveBiomeKeys(biomeScatter)); - } - - KList getBiomeSkyScatterResolved() { - KList cached = biomeSkyScatterResolved.getIfPresent(); - - if (cached != null) { - return cached; - } - - return biomeSkyScatterResolved.aquire(() -> IrisBiomeDerivatives.resolveBiomeKeys(biomeSkyScatter)); - } - - public boolean isCustom() { - return getCustomDerivitives() != null && getCustomDerivitives().isNotEmpty(); - } - - public double getGenLinkMax(String loadKey, Engine engine) { - return IrisBiomeGenLinks.getGenLinkMax(this, loadKey, engine); - } - - public double getGenLinkMin(String loadKey, Engine engine) { - return IrisBiomeGenLinks.getGenLinkMin(this, loadKey, engine); - } - - public IrisBiomeGeneratorLink getGenLink(String loadKey) { - return IrisBiomeGenLinks.getGenLink(this, loadKey); - } - - public double getHeight(Engine xg, double x, double z, long seed) { - double height = 0; - - for (IrisBiomeGeneratorLink i : generators) { - height += i.getHeight(xg, x, z, seed); - } - - return Math.max(0, Math.min(height, xg.getHeight())); - } - - public CNG getBiomeGenerator(RNG random) { - IrisData loader = getLoader(); - Engine engine = resolveBiomeGeneratorEngine(loader); - return getBiomeGenerator(random, engine); - } - - public CNG getBiomeGenerator(RNG random, Engine engine) { - IrisData loader = getLoader(); - long seed = engine == null ? random.getSeed() : engine.getSeedManager().getBiome(); - SeededBiomeGenerator recent = recentBiomeGenerator; - if (recent != null && recent.seed == seed) { - return recent.generator; - } - - CNG generator = biomeGenerators.computeIfAbsent(seed, ignored -> createBiomeGenerator(seed, loader)); - recentBiomeGenerator = new SeededBiomeGenerator(seed, generator); - return generator; - } - - private Engine resolveBiomeGeneratorEngine(IrisData loader) { - IrisContext context = IrisContext.get(); - if (context != null) { - Engine contextEngine = context.getEngine(); - if (!contextEngine.isClosed() && (loader == null || contextEngine.getData() == loader)) { - return contextEngine; - } - } - - return loader == null ? null : loader.getEngine(); - } - - private CNG createBiomeGenerator(long seed, IrisData loader) { - int signature = 213949 + 228888 + getRarity() + getName().length(); - return biomeStyle.createNoCache(new RNG(seed).nextParallelRNG(signature), loader); - } - - public CNG getChildrenGenerator(RNG random, int sig, double scale) { - return childrenCell.aquire(() -> getChildStyle().create(random.nextParallelRNG(sig * 2137), getLoader()).bake().scale(scale).bake()); - } - - public boolean isLand() { - if (inferredType == null) { - return true; - } - - return inferredType.equals(InferredType.LAND); - } - - public boolean isSea() { - if (inferredType == null) { - return false; - } - return inferredType.equals(InferredType.SEA); - } - - public boolean isAquatic() { - return isSea(); - } - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean isShore() { - if (inferredType == null) { - return false; - } - return inferredType.equals(InferredType.SHORE); - } - - public Biome getSkyBiome(RNG rng, double x, double y, double z) { - return IrisBiomeDerivatives.getSkyBiome(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z); - } - - public Biome getSkyBiome(RNG rng, Engine engine, double x, double y, double z) { - return IrisBiomeDerivatives.getSkyBiome(this, rng, engine, x, y, z); - } - - public IrisBiomeCustom getCustomBiome(RNG rng, double x, double y, double z) { - return IrisBiomeDerivatives.getCustomBiome(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z); - } - - public IrisBiomeCustom getCustomBiome(RNG rng, Engine engine, double x, double y, double z) { - return IrisBiomeDerivatives.getCustomBiome(this, rng, engine, x, y, z); - } - - public KList getRealChildren(DataProvider g) { - return realChildren.aquire(() -> - { - KList realChildren = new KList<>(); - - for (String i : getChildren()) { - realChildren.add(g.getData().getBiomeLoader().load(i)); - } - - return realChildren; - }); - } - - public KList getAllChildren(DataProvider g, int limit) { - KSet m = new KSet<>(); - m.addAll(getChildren()); - limit--; - - if (limit > 0) { - for (String i : getChildren()) { - IrisBiome b = g.getData().getBiomeLoader().load(i); - m.addAll(b.getAllChildren(g, limit)); - } - } - - return new KList<>(m); - } - - //TODO: Test - public Biome getGroundBiome(RNG rng, double x, double y, double z) { - return IrisBiomeDerivatives.getGroundBiome(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z); - } - - public Biome getGroundBiome(RNG rng, Engine engine, double x, double y, double z) { - return IrisBiomeDerivatives.getGroundBiome(this, rng, engine, x, y, z); - } - - public String getSkyBiomeKey(RNG rng, double x, double y, double z) { - return IrisBiomeDerivatives.getSkyBiomeKey(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z); - } - - public String getSkyBiomeKey(RNG rng, Engine engine, double x, double y, double z) { - return IrisBiomeDerivatives.getSkyBiomeKey(this, rng, engine, x, y, z); - } - - public String getGroundBiomeKey(RNG rng, double x, double y, double z) { - return IrisBiomeDerivatives.getGroundBiomeKey(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z); - } - - public String getGroundBiomeKey(RNG rng, Engine engine, double x, double y, double z) { - return IrisBiomeDerivatives.getGroundBiomeKey(this, rng, engine, x, y, z); - } - - public Color getColor(Engine engine, RenderType type) { - return IrisBiomeColorRenderer.getColor(this, engine, type); - } - - @Override - public String getFolderName() { - return "biomes"; - } - - public String getTypeName() { - return "Biome"; - } - - private static final class SeededBiomeGenerator { - private final long seed; - private final CNG generator; - - private SeededBiomeGenerator(long seed, CNG generator) { - this.seed = seed; - this.generator = generator; - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeColorRenderer.java b/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeColorRenderer.java deleted file mode 100644 index 5f2b550ae..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeColorRenderer.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.world.biome; - -import art.arcane.iris.builtin.decorant.DecorantSettings; -import art.arcane.iris.builtin.decorant.DecoratorLoad; -import art.arcane.iris.builtin.terrain.LayerLoad; -import art.arcane.iris.builtin.terrain.LayersSettings; -import art.arcane.iris.engine.object.placement.ObjectPlacements; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.render.RenderType; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.volmlib.util.data.VanillaBiomeColors; -import art.arcane.volmlib.util.inventorygui.RandomColor; - -import java.awt.Color; - -/** - * Map / render color resolution for {@link IrisBiome}. IrisBiome is Gson deserialized from pack - * JSON, so its fields stay put and only the behavior lives here. - */ -final class IrisBiomeColorRenderer { - private IrisBiomeColorRenderer() { - } - - static Color getColor(IrisBiome biome, Engine engine, RenderType type) { - switch (type) { - case BIOME, HEIGHT, CAVE_LAND, REGION, BIOME_SEA, BIOME_LAND -> { - return biome.getCacheColor().aquire(() -> { - if (biome.getColor() == null) { - RandomColor randomColor = new RandomColor(biome.getName().hashCode()); - String vanillaKey = biome.getVanillaDerivativeKey(); - RandomColor.Color col = vanillaKey == null ? null : VanillaBiomeColors.getColorType(vanillaKey); - if (col == null) { - IrisLogging.warn("No vanilla biome found for " + biome.getName()); - return new Color(randomColor.randomColor()); - } - RandomColor.Luminosity lum = VanillaBiomeColors.getColorLuminosity(vanillaKey); - RandomColor.SaturationType sat = VanillaBiomeColors.getColorSaturation(vanillaKey); - int newColorI = randomColor.randomColor(col, col == RandomColor.Color.MONOCHROME ? RandomColor.SaturationType.MONOCHROME : sat, lum); - - return new Color(newColorI); - } - - try { - return Color.decode(biome.getColor()); - } catch (NumberFormatException e) { - IrisLogging.warn("Could not parse color \"" + biome.getColor() + "\" for biome " + biome.getName()); - return new Color(new RandomColor(biome.getName().hashCode()).randomColor()); - } - }); - } - case OBJECT_LOAD -> { - return biome.getCacheColorObjectDensity().aquire(() -> { - double density = 0; - - for (IrisObjectPlacement i : ObjectPlacements.all(biome)) { - density += i.getDensity() * i.getChance(); - } - - return Color.getHSBColor(0.225f, (float) (density / engine.getMaxBiomeObjectDensity()), 1f); - }); - } - case DECORATOR_LOAD -> { - return biome.getCacheColorDecoratorLoad().aquire(() -> { - double busiest = 0D; - for (IrisBiome reachable : engine.getDimension().getReachableBiomes(engine)) { - busiest = Math.max(busiest, DecoratorLoad.of(decorantSettingsOf(reachable))); - } - return Color.getHSBColor(0.41f, (float) (DecoratorLoad.colour(decorantSettingsOf(biome)) / busiest), 1f); - }); - } - case LAYER_LOAD -> { - return biome.getCacheColorLayerLoad().aquire(() -> { - double busiest = 0D; - for (IrisBiome reachable : engine.getDimension().getReachableBiomes(engine)) { - busiest = Math.max(busiest, layerCountOf(reachable)); - } - return Color.getHSBColor(0.625f, (float) (layerCountOf(biome) / busiest), 1f); - }); - } - } - - return Color.black; - } - - private static int layerCountOf(IrisBiome biome) { - return LayerLoad.layersOf(biome.getModuleSettings().find(LayersSettings.class).orElse(null)).size(); - } - - private static DecorantSettings decorantSettingsOf(IrisBiome biome) { - return biome.getModuleSettings().find(DecorantSettings.class).orElse(null); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeDerivatives.java b/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeDerivatives.java deleted file mode 100644 index 5813c9475..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeDerivatives.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.world.biome; - -import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.util.common.data.registry.RegistryUtil; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import org.bukkit.NamespacedKey; -import org.bukkit.block.Biome; - -/** - * Vanilla derivative and biome scatter resolution for {@link IrisBiome}. IrisBiome is Gson - * deserialized from pack JSON, so its fields stay put and only the behavior lives here. - */ -final class IrisBiomeDerivatives { - private IrisBiomeDerivatives() { - } - - static String namespacedBiomeKey(String key) { - if (key == null || key.isBlank()) { - return null; - } - String trimmed = key.trim(); - return trimmed.indexOf(':') >= 0 ? trimmed : "minecraft:" + trimmed; - } - - static String getVanillaDerivativeKey(String derivative, String vanillaDerivative) { - String resolved = namespacedBiomeKey(vanillaDerivative); - return resolved == null ? namespacedBiomeKey(derivative) : resolved; - } - - static String getStructureDerivativeKey(IrisBiome biome) { - String key = biome.getVanillaDerivativeKey(); - if (key == null || !key.startsWith("minecraft:")) { - return key; - } - if (biome.isSea() && !isVanillaSeaStructureBiome(key)) { - return "minecraft:the_void"; - } - if (biome.isShore() && !isVanillaShoreStructureBiome(key)) { - return "minecraft:beach"; - } - return key; - } - - static boolean isVanillaSeaStructureBiome(String key) { - return key != null && (key.contains("ocean") || key.endsWith("river")); - } - - static boolean isVanillaShoreStructureBiome(String key) { - return key != null && (key.endsWith("beach") || key.endsWith("shore")); - } - - static KList resolveBiomeKeys(KList keys) { - KList resolved = new KList<>(); - for (String key : keys) { - resolved.add(resolveBiomeKey(key)); - } - return resolved; - } - - static Biome resolveBiomeKey(String key) { - if (key == null) { - return null; - } - NamespacedKey namespacedKey = NamespacedKey.fromString(key); - return namespacedKey == null ? null : RegistryUtil.lookup(Biome.class).get(namespacedKey); - } - - static Biome getSkyBiome(IrisBiome biome, RNG rng, Engine engine, double x, double y, double z) { - KList biomeSkyScatter = biome.getBiomeSkyScatter(); - - if (biomeSkyScatter.size() == 1) { - return biome.getBiomeSkyScatterResolved().get(0); - } - - if (biomeSkyScatter.isEmpty()) { - return getGroundBiome(biome, rng, engine, x, y, z); - } - - return biome.getBiomeSkyScatterResolved().get(biome.getBiomeGenerator(rng, engine).fit(0, biomeSkyScatter.size() - 1, x, y, z)); - } - - static Biome getGroundBiome(IrisBiome biome, RNG rng, Engine engine, double x, double y, double z) { - KList biomeScatter = biome.getBiomeScatter(); - - if (biomeScatter.isEmpty()) { - return biome.getDerivative(); - } - - if (biomeScatter.size() == 1) { - return biome.getBiomeScatterResolved().get(0); - } - - return biome.getBiomeGenerator(rng, engine).fit(biome.getBiomeScatterResolved(), x, y, z); - } - - static String getSkyBiomeKey(IrisBiome biome, RNG rng, Engine engine, double x, double y, double z) { - KList biomeSkyScatter = biome.getBiomeSkyScatter(); - - if (biomeSkyScatter.size() == 1) { - return namespacedBiomeKey(biomeSkyScatter.get(0)); - } - - if (biomeSkyScatter.isEmpty()) { - return getGroundBiomeKey(biome, rng, engine, x, y, z); - } - - return namespacedBiomeKey(biomeSkyScatter.get(biome.getBiomeGenerator(rng, engine).fit(0, biomeSkyScatter.size() - 1, x, y, z))); - } - - static String getGroundBiomeKey(IrisBiome biome, RNG rng, Engine engine, double x, double y, double z) { - KList biomeScatter = biome.getBiomeScatter(); - - if (biomeScatter.isEmpty()) { - return biome.getDerivativeKey(); - } - - if (biomeScatter.size() == 1) { - return namespacedBiomeKey(biomeScatter.get(0)); - } - - return namespacedBiomeKey(biomeScatter.get(biome.getBiomeGenerator(rng, engine).fit(0, biomeScatter.size() - 1, x, y, z))); - } - - static IrisBiomeCustom getCustomBiome(IrisBiome biome, RNG rng, Engine engine, double x, double y, double z) { - KList customDerivitives = biome.getCustomDerivitives(); - - if (customDerivitives.size() == 1) { - return customDerivitives.get(0); - } - - return customDerivitives.get(biome.getBiomeGenerator(rng, engine).fit(0, customDerivitives.size() - 1, x, y, z)); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeGenLinks.java b/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeGenLinks.java deleted file mode 100644 index 03ba55104..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeGenLinks.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.world.biome; - -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.volmlib.util.collection.KMap; - -/** - * Generator link lookups for {@link IrisBiome}. IrisBiome is Gson deserialized from pack JSON, so - * its fields stay put and only the behavior lives here. These are resolved per generation column, - * so the caches are read through {@link AtomicCache#getIfPresent()} first. - */ -final class IrisBiomeGenLinks { - private IrisBiomeGenLinks() { - } - - static double getGenLinkMax(IrisBiome biome, String loadKey, Engine engine) { - if (loadKey == null || loadKey.isBlank()) { - return 0; - } - - Integer v = maxIndex(biome).get(loadKey); - - return v == null ? 0 : v; - } - - static double getGenLinkMin(IrisBiome biome, String loadKey, Engine engine) { - if (loadKey == null || loadKey.isBlank()) { - return 0; - } - - Integer v = minIndex(biome).get(loadKey); - - return v == null ? 0 : v; - } - - static IrisBiomeGeneratorLink getGenLink(IrisBiome biome, String loadKey) { - if (loadKey == null || loadKey.isBlank()) { - return null; - } - - return linkIndex(biome).get(loadKey); - } - - private static KMap maxIndex(IrisBiome biome) { - AtomicCache> cache = biome.getGenCacheMax(); - KMap cached = cache.getIfPresent(); - - if (cached != null) { - return cached; - } - - return cache.aquire(() -> - { - KMap l = new KMap<>(); - - for (IrisBiomeGeneratorLink i : biome.getGenerators()) { - String generatorKey = i.getGenerator(); - if (generatorKey == null || generatorKey.isBlank()) { - continue; - } - - l.put(generatorKey, i.getMax()); - - } - - return l; - }); - } - - private static KMap minIndex(IrisBiome biome) { - AtomicCache> cache = biome.getGenCacheMin(); - KMap cached = cache.getIfPresent(); - - if (cached != null) { - return cached; - } - - return cache.aquire(() -> - { - KMap l = new KMap<>(); - - for (IrisBiomeGeneratorLink i : biome.getGenerators()) { - String generatorKey = i.getGenerator(); - if (generatorKey == null || generatorKey.isBlank()) { - continue; - } - - l.put(generatorKey, i.getMin()); - } - - return l; - }); - } - - private static KMap linkIndex(IrisBiome biome) { - AtomicCache> cache = biome.getGenCache(); - KMap cached = cache.getIfPresent(); - - if (cached != null) { - return cached; - } - - return cache.aquire(() -> - { - KMap l = new KMap<>(); - - for (IrisBiomeGeneratorLink i : biome.getGenerators()) { - String generatorKey = i.getGenerator(); - if (generatorKey == null || generatorKey.isBlank()) { - continue; - } - - l.put(generatorKey, i); - } - - return l; - }); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeGeneratorLink.java b/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeGeneratorLink.java deleted file mode 100644 index 5f2cdc5ea..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeGeneratorLink.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.world.biome; - -import art.arcane.iris.engine.object.terrain.IrisGenerator; -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.object.annotations.DependsOn; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.util.common.data.DataProvider; -import art.arcane.iris.util.project.interpolation.IrisInterpolation; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("generator-layer") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("This represents a link to a generator for a biome") -@Data -public class IrisBiomeGeneratorLink { - - private final transient AtomicCache gen = new AtomicCache<>(); - @RegistryListResource(IrisGenerator.class) - @Desc("The generator id") - private String generator = "default"; - @DependsOn({"min", "max"}) - @Required - @MinNumber(-2032) - @MaxNumber(2032) - @Desc("The min block value (value + fluidHeight)") - private int min = 0; - @DependsOn({"min", "max"}) - @Required - @MinNumber(-2032) - @MaxNumber(2032) - @Desc("The max block value (value + fluidHeight)") - private int max = 0; - - public IrisGenerator getCachedGenerator(DataProvider g) { - return gen.aquire(() -> { - String generatorKey = getGenerator(); - if (generatorKey == null || generatorKey.isBlank()) { - generatorKey = "default"; - } - - IrisGenerator gen = g.getData().getGeneratorLoader().load(generatorKey); - - if (gen == null) { - gen = new IrisGenerator(); - } - - if (gen.getLoadKey() == null || gen.getLoadKey().isBlank()) { - gen.setLoadKey(generatorKey); - } - - return gen; - }); - } - - public double getHeight(DataProvider xg, double x, double z, long seed) { - double g = getCachedGenerator(xg).getHeight(x, z, seed); - g = g < 0 ? 0 : g; - g = g > 1 ? 1 : g; - - return IrisInterpolation.lerp(min, max, g); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustom.java b/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustom.java deleted file mode 100644 index ebd3ae383..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustom.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.world.biome.custom; - -import art.arcane.iris.core.nms.datapack.IDataFixer; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.DependsOn; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.collection.KMap; -import art.arcane.volmlib.util.json.JSONArray; -import art.arcane.volmlib.util.json.JSONObject; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.awt.Color; -import java.util.Locale; - -@Snippet("custom-biome") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A custom biome, generated through a datapack") -@Data -public class IrisBiomeCustom { - @Required - @Desc("The resource key of this biome. Just a simple id such as 'plains' or something.") - private String id = ""; - - @MinNumber(-3) - @MaxNumber(3) - @Desc("The biome's temperature") - private double temperature = 0.8; - - @MinNumber(-3) - @MaxNumber(3) - @Desc("The biome's downfall amount (snow / rain), see preci") - private double humidity = 0.4; - - @DependsOn("spawnRarity") - @ArrayType(min = 1, type = IrisBiomeCustomSpawn.class) - @Desc("The biome's mob spawns") - private KList spawns = new KList<>(); - - @ArrayType(min = 1, type = String.class) - @Desc("Biome tags to opt this custom biome into, such as minecraft:allows_surface_slime_spawns") - private KList tags = new KList<>(); - - @Desc("The biome's downfall type") - private IrisBiomeCustomPrecipType downfallType = IrisBiomeCustomPrecipType.rain; - - @Desc("Define an ambient particle to be rendered clientside (no server cost!)") - private IrisBiomeCustomParticle ambientParticle = null; - - @Required - @Desc("The biome's category type") - private IrisBiomeCustomCategory category = IrisBiomeCustomCategory.plains; - - @MinNumber(0) - @MaxNumber(20) - @Desc("The spawn rarity of any defined spawners") - private int spawnRarity = 0; - - @Desc("The color of the sky, top half of sky. (hex format)") - private String skyColor = "#79a8e1"; - - @Desc("The color of the fog, bottom half of sky. (hex format)") - private String fogColor = "#c0d8e1"; - - @Desc("The color of the water (hex format). Leave blank / don't define to not change") - private String waterColor = "#3f76e4"; - - @Desc("The color of water fog (hex format). Leave blank / don't define to not change") - private String waterFogColor = "#050533"; - - @Desc("The color of the grass (hex format). Leave blank / don't define to not change") - private String grassColor = ""; - - @Desc("The color of foliage (hex format). Leave blank / don't define to not change") - private String foliageColor = ""; - - /** - * The tags this custom biome is installed into: the pack author's own {@code tags} plus the direct tag - * membership of the Iris biome's vanilla derivative. Inheriting the derivative's tags is what makes - * {@code #minecraft:is_overworld} and every mod-authored tag selector resolve against Iris custom biomes; - * without it a custom biome sits in no tag at all and mod content that gates on tags silently never runs. - * - *

Author tags win order but duplicates collapse: the tag files are written through a sorted set. - * Structure tags ({@code has_structure/*}) are deliberately not inherited - native structure placement - * resolves through the biome's structure derivative, so injecting them would place a structure twice. - * - * @param vanillaDerivativeKey the owning Iris biome's vanilla derivative key, may be null - */ - public KList getEffectiveTags(String vanillaDerivativeKey) { - KList resolved = new KList<>(); - KList authored = getTags(); - - if (authored != null) { - for (String tag : authored) { - resolved.addIfMissing(tag); - } - } - - for (String inherited : IrisVanillaBiomeTags.tagsFor(vanillaDerivativeKey)) { - resolved.addIfMissing(inherited); - } - - return resolved; - } - - public String generateJson(IDataFixer fixer) { - JSONObject effects = new JSONObject(); - effects.put("sky_color", parseColor(getSkyColor())); - effects.put("fog_color", parseColor(getFogColor())); - effects.put("water_color", parseColor(getWaterColor())); - effects.put("water_fog_color", parseColor(getWaterFogColor())); - - if (ambientParticle != null) { - // Never touch IrisBiomeCustomParticle.getParticle() here: it returns a Bukkit Particle - // and this method also runs during modded datapack staging. - String particleKey = ambientParticle.getParticleKey(); - if (particleKey == null) { - IrisLogging.warn("Custom biome " + getId() + " declares an ambientParticle with no particle key, skipping it"); - } else { - JSONObject particle = new JSONObject(); - JSONObject po = new JSONObject(); - po.put("type", particleKey); - particle.put("options", po); - particle.put("probability", 1f / ambientParticle.getRarity()); - effects.put("particle", particle); - } - } - - if (!getGrassColor().isEmpty()) { - effects.put("grass_color", parseColor(getGrassColor())); - } - - if (!getFoliageColor().isEmpty()) { - effects.put("foliage_color", parseColor(getFoliageColor())); - } - - JSONObject j = new JSONObject(); - j.put("surface_builder", "minecraft:grass"); - j.put("depth", 0.125); - j.put("scale", 0.05); - j.put("temperature", getTemperature()); - j.put("downfall", getHumidity()); - j.put("creature_spawn_probability", getSpawnRarity()); - j.put("has_precipitation", getDownfallType() != IrisBiomeCustomPrecipType.none); - j.put("precipitation", getDownfallType().toString().toLowerCase()); - j.put("category", getCategory().toString().toLowerCase()); - j.put("effects", effects); - j.put("starts", new JSONArray()); - j.put("spawners", new JSONObject()); - j.put("spawn_costs", new JSONObject()); - j.put("carvers", new JSONObject()); - j.put("features", new JSONArray()); - - if (spawnRarity > 0) { - j.put("creature_spawn_probability", spawnRarity); - } - - if (getSpawns() != null && getSpawns().isNotEmpty()) { - JSONObject spawners = new JSONObject(); - KMap groups = new KMap<>(); - - for (IrisBiomeCustomSpawn i : getSpawns()) { - if (i == null) { - continue; - } - String key = i.getTypeKey(); - if (key == null) { - IrisLogging.warn("Skipping custom biome spawn with null entity type in biome " + getId()); - continue; - } - IrisBiomeCustomSpawnType group = i.getGroup() == null ? IrisBiomeCustomSpawnType.MISC : i.getGroup(); - JSONArray g = groups.computeIfAbsent(group, (k) -> new JSONArray()); - JSONObject o = new JSONObject(); - o.put("type", key); - o.put("weight", i.getWeight()); - o.put("minCount", i.getMinCount()); - o.put("maxCount", i.getMaxCount()); - g.put(o); - } - - for (IrisBiomeCustomSpawnType i : groups.k()) { - spawners.put(i.name().toLowerCase(Locale.ROOT), groups.get(i)); - } - - j.put("spawners", spawners); - } - - return fixer.fixCustomBiome(this, j).toString(4); - } - - private int parseColor(String c) { - String v = (c.startsWith("#") ? c : "#" + c).trim(); - try { - return Color.decode(v).getRGB() & 0x00FFFFFF; - } catch (Throwable e) { - IrisLogging.reportError(e); - IrisLogging.error("Error Parsing '''color''', (" + c + ")"); - } - - return 0; - } - - public String getId() { - return id.toLowerCase(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomParticle.java b/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomParticle.java deleted file mode 100644 index d0d9117ea..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomParticle.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.world.biome.custom; - -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.util.common.data.registry.RegistryUtil; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.NamespacedKey; -import org.bukkit.Particle; - -@Snippet("custom-biome-particle") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A custom biome ambient particle") -@Data -public class IrisBiomeCustomParticle { - private final transient AtomicCache particleResolved = new AtomicCache<>(); - @Required - @Desc("The biome's particle type") - private String particle = "minecraft:flash"; - - @MinNumber(1) - @MaxNumber(10000) - @Desc("The rarity") - private int rarity = 35; - - /** - * The authored particle key, normalized to a namespaced key. Platform-neutral: datapack - * emission must use this and never {@link #getParticle()}, which only resolves on Bukkit. - */ - public String getParticleKey() { - if (particle == null || particle.isEmpty()) { - return null; - } - return particle.indexOf(':') >= 0 ? particle : "minecraft:" + particle; - } - - public Particle getParticle() { - return particleResolved.aquire(() -> { - NamespacedKey namespacedKey = NamespacedKey.fromString(particle); - return namespacedKey == null ? null : RegistryUtil.lookup(Particle.class).get(namespacedKey); - }); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomSpawn.java b/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomSpawn.java deleted file mode 100644 index 8abd73a04..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomSpawn.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.world.biome.custom; - -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListEntityType; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.util.common.data.registry.RegistryUtil; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.NamespacedKey; -import org.bukkit.entity.EntityType; - -import java.util.Locale; - -@Snippet("custom-biome-spawn") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A custom biome spawn") -@Data -public class IrisBiomeCustomSpawn { - private final transient AtomicCache typeResolved = new AtomicCache<>(); - @Required - @RegistryListEntityType - @Desc("The biome's entity type") - private String type = "minecraft:cow"; - - public EntityType getType() { - String typeKey = getTypeKey(); - if (typeKey == null) { - return null; - } - return typeResolved.aquire(() -> { - NamespacedKey namespacedKey = NamespacedKey.fromString(typeKey); - return namespacedKey == null ? null : RegistryUtil.lookup(EntityType.class).get(namespacedKey); - }); - } - - public String getTypeKey() { - if (type == null || type.isBlank()) { - return null; - } - String normalized = type.trim().toLowerCase(Locale.ROOT); - return normalized.contains(":") ? normalized : "minecraft:" + normalized; - } - - @MinNumber(1) - @Desc("The min to spawn") - private int minCount = 2; - - @MinNumber(1) - @Desc("The max to spawn") - private int maxCount = 5; - - @MinNumber(1) - @MaxNumber(1000) - @Desc("The weight in this group. Higher weight, the more common this type is spawned") - private int weight = 1; - - @Desc("The rarity") - private IrisBiomeCustomSpawnType group = IrisBiomeCustomSpawnType.MISC; -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimension.java b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimension.java deleted file mode 100644 index 24f593cf1..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimension.java +++ /dev/null @@ -1,723 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.world.dimension; - -import art.arcane.iris.engine.object.image.IrisImageMap; -import art.arcane.iris.engine.object.image.IrisImageMapApplication; -import art.arcane.iris.engine.object.image.IrisImageMapBinding; -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.noise.IrisShapedGeneratorStyle; -import art.arcane.iris.engine.object.noise.NoiseStyle; -import art.arcane.iris.engine.object.runtime.StudioMode; -import art.arcane.iris.engine.object.value.IrisRange; -import art.arcane.iris.engine.object.world.IrisEnvironment; -import art.arcane.iris.engine.object.world.IrisWorldBoundary; -import art.arcane.iris.engine.object.world.biome.InferredType; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.core.IrisDatapackCompiler.DimensionHeight; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.core.nms.datapack.DataVersion; -import art.arcane.iris.core.nms.datapack.IDataFixer; -import art.arcane.iris.core.nms.datapack.IDataFixer.Dimension; -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListFunction; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.functions.ComponentFlagFunction; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.collection.KMap; -import art.arcane.volmlib.util.collection.KSet; -import art.arcane.iris.util.common.data.DataProvider; -import art.arcane.volmlib.util.io.IO; -import art.arcane.volmlib.util.json.JSONArray; -import art.arcane.volmlib.util.json.JSONObject; -import art.arcane.volmlib.util.math.Position2; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.util.project.noise.CNG; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.ToString; -import lombok.experimental.Accessors; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.AtomicMoveNotSupportedException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import java.util.regex.Pattern; - -@Accessors(chain = true) -@NoArgsConstructor -@Desc("Represents a dimension") -@Data -@EqualsAndHashCode(callSuper = false, doNotUseGetters = true) -@ToString(doNotUseGetters = true) -public class IrisDimension extends IrisRegistrant { - private static final Pattern RESOURCE_KEY_PATTERN = Pattern.compile("[a-z0-9_.-]+:[a-z0-9/._-]+"); - - private final transient AtomicCache parallaxSize = new AtomicCache<>(); - private final transient AtomicCache rockLayerGenerator = new AtomicCache<>(); - private final transient AtomicCache fluidLayerGenerator = new AtomicCache<>(); - private final transient AtomicCache coordFracture = new AtomicCache<>(); - private final transient AtomicCache sinr = new AtomicCache<>(); - private final transient AtomicCache cosr = new AtomicCache<>(); - private final transient AtomicCache rad = new AtomicCache<>(); - private final transient AtomicCache featuresUsed = new AtomicCache<>(); - @MinNumber(2) - @Required - @Desc("The human readable name of this dimension") - private String name = "A Dimension"; - @MinNumber(1) - @MaxNumber(2032) - @Desc("Maximum height at which players can be teleported to through gameplay.") - private int logicalHeight = 256; - @Desc("If set to true, Iris will remove chunks to allow visualizing cross sections of chunks easily") - private boolean debugChunkCrossSections = false; - @Desc("Studio Mode for testing different parts of the world") - private StudioMode studioMode = StudioMode.NORMAL; - @MinNumber(2) - @MaxNumber(16) - @Desc("Every X/Z % debugCrossSectionsMod == 0 cuts the chunk") - private int debugCrossSectionsMod = 3; - @MinNumber(0) - @Desc("The version of this dimension. Changing this will stop users from accidentally upgrading (and breaking their worlds).") - private int version = 1; - @MinNumber(0) - @MaxNumber(1) - @Desc("The land chance. Up to 1.0 for total land or 0.0 for total sea") - private double landChance = 0.625; - @Desc("The placement style of regions") - private IrisGeneratorStyle regionStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - @Desc("The placement style of land/sea") - private IrisGeneratorStyle continentalStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - @Desc("The noise style used to select land biomes within a region") - private IrisGeneratorStyle landBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - @Desc("The noise style used to select shore biomes within a region") - private IrisGeneratorStyle shoreBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - @Desc("The noise style used to select sea biomes within a region") - private IrisGeneratorStyle seaBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - @Desc("The noise style used to select cave biomes within a region") - private IrisGeneratorStyle caveBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - @Desc("Instead of filling objects with air, fills them with cobweb so you can see them") - private boolean debugSmartBore = false; - @Desc("The world environment") - private IrisEnvironment environment = IrisEnvironment.NORMAL; - @RegistryListResource(IrisRegion.class) - @Required - @ArrayType(min = 1, type = String.class) - @Desc("Define all of the regions to include in this dimension. Dimensions -> Regions -> Biomes -> Objects etc") - private KList regions = new KList<>(); - @Required - @MinNumber(0) - @MaxNumber(1024) - @Desc("The fluid (sea level) height for this dimension, in world Y. Water fills every sea column up to this height, so 63 puts the water surface at world Y 63.") - private int fluidHeight = 63; - @Desc("Define the min and max Y bounds of this dimension. Please keep in mind that Iris internally generates from 0 to (max - min). \n\nFor example at -64 to 320, Iris is internally generating to 0 to 384, then on outputting chunks, it shifts it down by the min height (64 blocks). The default is -64 to 320. \n\nfluidHeight stays in world Y: the engine converts it internally by subtracting the min height, so a fluid height of 63 shows up in the world at Y 63.") - private IrisRange dimensionHeight = new IrisRange(-64, 320); - @Desc("Define options for this dimension") - private IrisDimensionTypeOptions dimensionOptions = new IrisDimensionTypeOptions(); - @Desc("Configure and enforce the native Minecraft world border. When omitted, Iris leaves the native border unchanged.") - private IrisWorldBoundary worldBoundary = null; - @ArrayType(type = IrisImageMapBinding.class) - @Desc("Bind reusable image-map resources to typed world-generation inputs") - private KList imageMaps = new KList<>(); - @Desc("When true, sets the dimension's ambient light to maximum, making all blocks fully lit regardless of light level.") - private boolean fullbright = false; - @RegistryListResource(IrisDimension.class) - @Desc("When set, generates the referenced dimension's terrain upside-down at the world ceiling, creating a nether-like canopy. Use the dimension's load key (e.g., 'overworld'). Set to 'none' to disable.") - private String upperDimension = "none"; - @MinNumber(0) - @MaxNumber(256) - @Desc("Minimum air gap in blocks between the lower terrain surface and the upper terrain surface.") - private int upperDimensionGap = 32; - @RegistryListResource(IrisBiome.class) - @Desc("Keep this either undefined or empty. Setting any biome name into this will force iris to only generate the specified biome. Great for testing.") - private String focus = ""; - @RegistryListResource(IrisRegion.class) - @Desc("Keep this either undefined or empty. Setting any region name into this will force iris to only generate the specified region. Great for testing.") - private String focusRegion = ""; - @MinNumber(0.0001) - @MaxNumber(512) - @Desc("Zoom in or out the biome size. Higher = bigger biomes") - private double biomeZoom = 1D; - @MinNumber(0) - @MaxNumber(360) - @Desc("You can rotate the input coordinates by an angle. This can make terrain appear more natural (less sharp corners and lines). This literally rotates the entire dimension by an angle. Hint: Try 12 degrees or something not on a 90 or 45 degree angle.") - private double dimensionAngleDeg = 0; - @MinNumber(0) - @MaxNumber(8192) - @Desc("Coordinate fracturing applies noise to the input coordinates. This creates the 'iris swirls' and wavy features. The distance pushes these waves further into places they shouldnt be. This is a block value multiplier.") - private double coordFractureDistance = 20; - @MinNumber(0.0001) - @MaxNumber(512) - @Desc("Coordinate fracturing zoom. Higher = less frequent warping, Lower = more frequent and rapid warping / swirls.") - private double coordFractureZoom = 8; - @MinNumber(0.0001) - @MaxNumber(512) - @Desc("This zooms in the land space") - private double landZoom = 1; - @MinNumber(0.0001) - @MaxNumber(512) - @Desc("This zooms oceanic biomes") - private double seaZoom = 1; - @MinNumber(0.0001) - @MaxNumber(512) - @Desc("Zoom in continents") - private double continentZoom = 1; - @MinNumber(0.0001) - @MaxNumber(512) - @Desc("Change the size of regions") - private double regionZoom = 1; - @Desc("Disable this to stop placing objects, entities, features & updates") - private boolean useMantle = true; - @Desc("Prevent Leaf decay as if placed in creative mode") - private boolean preventLeafDecay = false; - @ArrayType(min = 1, type = IrisShapedGeneratorStyle.class) - @Desc("Overlay additional noise on top of the interoplated terrain.") - private KList overlayNoise = new KList<>(); - @ArrayType(type = String.class, min = 1) - @Desc("External datapack sources owned by this dimension. Bukkit registers their resources server-wide, but Iris excludes their structure sets and definitions from generation and locate state in vanilla worlds and Iris dimensions that do not declare the same source. Editable auto-import is limited to resources supplied by the URLs declared by each Iris pack. Any registered datapack structure can be placed directly through nativeStructures without conversion. Replacing native generation requires a dimension-level structure placement with nativeSuppression set to REPLACE_SOURCE; provenance alone never disables native structures.") - private KList datapackImports = new KList<>(); - @RegistryListFunction(ComponentFlagFunction.class) - @ArrayType(type = String.class) - @Desc("Mantle passes to skip in this dimension: CARVED (caves), OBJECT (objects), FLOATING_OBJECT (objects on floating islands) or JIGSAW (structures), or the id of a pack module's mantle stage, such as example:moss/veins. A name that matches nothing is warned about and ignored.") - private KList disabledComponents = new KList<>(); - - public int getMaxHeight() { - return (int) getDimensionHeight().getMax(); - } - - public int getMinHeight() { - return (int) getDimensionHeight().getMin(); - } - - public int getFluidHeight() { - return fluidHeight - (int) dimensionHeight.getMin(); - } - - public CNG getCoordFracture(RNG rng, int signature) { - return coordFracture.aquire(() -> - { - CNG coordFracture = CNG.signature(rng.nextParallelRNG(signature)); - coordFracture.scale(0.012 / coordFractureZoom); - return coordFracture; - }); - } - - public double getDimensionAngle() { - return rad.aquire(() -> Math.toRadians(dimensionAngleDeg)); - } - - public boolean hasFocusRegion() { - return !focusRegion.equals(""); - } - - public String getFocusRegion() { - return focusRegion; - } - - public double sinRotate() { - return sinr.aquire(() -> Math.sin(getDimensionAngle())); - } - - public double cosRotate() { - return cosr.aquire(() -> Math.cos(getDimensionAngle())); - } - - public KList getAllRegions(DataProvider g) { - KMap regions = new KMap<>(); - - if (g == null) { - return regions.v(); - } - IrisData data = g.getData(); - if (data == null || data.getRegionLoader() == null) { - return regions.v(); - } - - for (String key : getRegions()) { - IrisRegion region = data.getRegionLoader().load(key); - if (region != null) { - regions.put(key, region); - } - } - for (IrisImageMapBinding binding : getImageMaps()) { - if (binding == null || binding.getApplication() != IrisImageMapApplication.REGION) { - continue; - } - IrisImageMap map = data.getImageMapLoader().load(binding.getMap()); - if (map == null || map.getColors() == null) { - continue; - } - for (String target : imageMapTargets(map)) { - String key = localImageMapTarget(target); - IrisRegion region = data.getRegionLoader().load(key); - if (region != null) { - regions.put(key, region); - } - } - } - return regions.v(); - } - - public KList getAllAnyRegions() { - KList r = new KList<>(); - - for (String i : getRegions()) { - r.add(IrisData.loadAnyRegion(i, getLoader())); - } - - return r; - } - - public KList getAllBiomes(DataProvider g) { - if (g == null) { - return new KList<>(); - } - IrisData data = g.getData(); - if (data == null || data.getBiomeLoader() == null) { - return new KList<>(); - } - return data.getBiomeLoader().loadAll(data.getBiomeLoader().getPossibleKeys()); - } - - public KList getReachableBiomes(DataProvider g) { - KMap biomes = new KMap<>(); - if (g == null) { - return biomes.v(); - } - - IrisData data = g.getData(); - if (data == null || data.getRegionLoader() == null || data.getBiomeLoader() == null) { - return biomes.v(); - } - - Deque pending = new ArrayDeque<>(); - for (IrisRegion region : getAllRegions(g)) { - if (region == null) { - continue; - } - addReachableBiomeKeys(pending, region.getAllBiomeIds()); - } - for (IrisImageMapBinding binding : getImageMaps()) { - if (binding == null || binding.getApplication() != IrisImageMapApplication.BIOME) { - continue; - } - IrisImageMap map = data.getImageMapLoader().load(binding.getMap()); - if (map == null) { - continue; - } - for (String target : imageMapTargets(map)) { - addReachableBiomeKey(pending, localImageMapTarget(target)); - } - } - - addReachableBiomeKeys(pending, getModuleSettings().usedBiomes(data.getPackResources(), getModuleSettings())); - - Set visited = new HashSet<>(); - while (!pending.isEmpty()) { - String biomeKey = pending.removeFirst(); - if (!visited.add(biomeKey)) { - continue; - } - - IrisBiome biome = data.getBiomeLoader().load(biomeKey); - if (biome == null) { - continue; - } - - String loadKey = biome.getLoadKey(); - if (loadKey == null || loadKey.isBlank() || biomes.containsKey(loadKey)) { - continue; - } - - visited.add(loadKey); - biomes.put(loadKey, biome); - addReachableBiomeKeys(pending, biome.getChildren()); - addReachableBiomeKeys(pending, biome.getModuleSettings().treeBiomes(data.getPackResources())); - addReachableBiomeKeys(pending, biome.getModuleSettings().usedBiomes(data.getPackResources(), getModuleSettings())); - } - - return biomes.v(); - } - - private Set imageMapTargets(IrisImageMap map) { - Set targets = new LinkedHashSet<>(); - if (map.getColors() != null) { - for (String target : map.getColors().values()) { - if (target != null && !target.isBlank()) { - targets.add(target); - } - } - } - if (map.getFallbackTarget() != null && !map.getFallbackTarget().isBlank()) { - targets.add(map.getFallbackTarget()); - } - return targets; - } - - private String localImageMapTarget(String target) { - return target.startsWith("iris:") ? target.substring("iris:".length()) : target; - } - - private void addReachableBiomeKeys(Deque pending, Iterable biomeKeys) { - if (biomeKeys == null) { - return; - } - for (String biomeKey : biomeKeys) { - addReachableBiomeKey(pending, biomeKey); - } - } - - private void addReachableBiomeKey(Deque pending, String biomeKey) { - if (biomeKey != null && !biomeKey.isBlank()) { - pending.addLast(biomeKey); - } - } - - public KList getAllAnyBiomes() { - KList r = new KList<>(); - - for (IrisRegion i : getAllAnyRegions()) { - if (i == null) { - continue; - } - - r.addAll(i.getAllAnyBiomes()); - } - - return r; - } - - public IrisGeneratorStyle getBiomeStyle(InferredType type) { - switch (type) { - case CAVE: - return caveBiomeStyle; - case LAND: - return landBiomeStyle; - case SEA: - return seaBiomeStyle; - case SHORE: - return shoreBiomeStyle; - default: - break; - } - - return landBiomeStyle; - } - - public void installBiomes(IDataFixer fixer, DataProvider data, KList datapackRoots, KSet biomes) throws IOException { - String namespace = getLoadKey().toLowerCase(Locale.ROOT); - installBiomes(fixer, data, datapackRoots, namespace, "", biomes); - } - - public void installBiomes(IDataFixer fixer, DataProvider data, KList datapackRoots, - String namespace, String pathPrefix, KSet biomes) throws IOException { - // Tag membership is accumulated in memory and flushed once per tag at the end of the walk. Writing a - // tag file per (biome, tag) pair made staging quadratic: every write re-read, re-parsed and re-emitted - // a file that grows with every biome added to that tag. - KMap> tagMembership = new KMap<>(); - - for (IrisBiome irisBiome : getAllBiomes(data)) { - if (!irisBiome.isCustom()) { - continue; - } - - // Tag membership is inherited from the biome's vanilla derivative so that #minecraft:is_overworld - // style selectors (vanilla's own, and every mod that writes them) hit Iris custom biomes. The - // features and carvers arrays in the emitted biome JSON stay empty: native feature passthrough - // comes from the chunk generator's generation-settings getter, not from the datapack. - String derivativeKey = irisBiome.getVanillaDerivativeKey(); - - for (IrisBiomeCustom customBiome : irisBiome.getCustomDerivitives()) { - String customBiomeId = customBiome.getId(); - String json = customBiome.generateJson(fixer); - - synchronized (biomes) { - if (!biomes.add(customBiomeId)) { - IrisLogging.debug("Duplicate Data Pack Biome: " + getLoadKey() + "/" + customBiomeId); - continue; - } - } - - String biomePath = pathPrefix.isBlank() - ? customBiomeId - : pathPrefix + "/" + customBiomeId; - for (File datapackRoot : datapackRoots) { - File output = new File(datapackRoot, "data/" + namespace + "/worldgen/biome/" + biomePath + ".json"); - - IrisLogging.debug(" Installing Data Pack Biome: " + output.getPath()); - output.getParentFile().mkdirs(); - IO.writeAll(output, json); - } - collectBiomeTags(tagMembership, namespace + ":" + biomePath, - customBiome.getEffectiveTags(derivativeKey)); - } - } - - for (File datapackRoot : datapackRoots) { - installBiomeTags(datapackRoot, tagMembership); - } - } - - public static void clearGeneratedBiomeTags(KList datapackRoots) { - for (File datapackRoot : datapackRoots) { - File dataFolder = new File(datapackRoot, "data"); - File[] namespaces = dataFolder.listFiles(File::isDirectory); - if (namespaces == null) { - continue; - } - for (File namespace : namespaces) { - IO.delete(new File(namespace, "tags/worldgen/biome")); - } - } - } - - /** - * Accumulates one biome's tag membership into the tag-to-biomes map. Normalization and rejection happen - * here so a malformed author tag is reported once, against the biome that declared it. - */ - static void collectBiomeTags(KMap> tagMembership, String biomeKey, KList tags) { - if (tags == null || tags.isEmpty()) { - return; - } - for (String rawTag : tags) { - String tag = normalizeResourceKey(rawTag); - if (tag == null) { - IrisLogging.error("Invalid custom biome tag '" + rawTag + "' for " + biomeKey); - continue; - } - tagMembership.computeIfAbsent(tag, ignored -> new KSet<>()).add(biomeKey); - } - } - - /** - * Writes every accumulated tag exactly once into one datapack root, merging with whatever a previous - * dimension or pack already wrote to the same file. - */ - static void installBiomeTags(File datapackRoot, KMap> tagMembership) throws IOException { - if (tagMembership == null || tagMembership.isEmpty()) { - return; - } - for (Map.Entry> entry : tagMembership.entrySet()) { - String tag = entry.getKey(); - int separator = tag.indexOf(':'); - String namespace = tag.substring(0, separator); - String path = tag.substring(separator + 1); - Path tagRoot = new File(datapackRoot, "data/" + namespace + "/tags/worldgen/biome").toPath() - .toAbsolutePath().normalize(); - Path output = tagRoot.resolve(path + ".json").normalize(); - if (!output.startsWith(tagRoot)) { - IrisLogging.error("Unsafe custom biome tag '" + tag + "' for " + entry.getValue()); - continue; - } - writeBiomeTag(output, entry.getValue()); - } - } - - private static String normalizeResourceKey(String key) { - if (key == null || key.isBlank()) { - return null; - } - String normalized = key.trim().toLowerCase(Locale.ROOT); - if (normalized.indexOf(':') < 0) { - normalized = "minecraft:" + normalized; - } - return RESOURCE_KEY_PATTERN.matcher(normalized).matches() ? normalized : null; - } - - static void writeBiomeTag(Path output, Set biomeKeys) throws IOException { - if (biomeKeys == null || biomeKeys.isEmpty()) { - return; - } - synchronized (IrisDimension.class) { - Set values = new TreeSet<>(); - if (Files.isRegularFile(output)) { - JSONObject existing = new JSONObject(Files.readString(output, StandardCharsets.UTF_8)); - JSONArray existingValues = existing.optJSONArray("values"); - if (existingValues != null) { - for (int index = 0; index < existingValues.length(); index++) { - String value = existingValues.optString(index, null); - if (value != null && !value.isBlank()) { - values.add(value); - } - } - } - } - values.addAll(biomeKeys); - - JSONArray outputValues = new JSONArray(); - for (String value : values) { - outputValues.put(value); - } - JSONObject tag = new JSONObject(); - tag.put("replace", false); - tag.put("values", outputValues); - writeAtomic(output, tag.toString(4)); - } - } - - private static void writeAtomic(Path output, String content) throws IOException { - Files.createDirectories(output.getParent()); - Path temporary = Files.createTempFile(output.getParent(), output.getFileName().toString(), ".tmp"); - try { - Files.writeString(temporary, content, StandardCharsets.UTF_8); - try { - Files.move(temporary, output, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); - } catch (AtomicMoveNotSupportedException e) { - Files.move(temporary, output, StandardCopyOption.REPLACE_EXISTING); - } - } finally { - Files.deleteIfExists(temporary); - } - } - - public Dimension getBaseDimension() { - return switch (environment) { - case NETHER -> Dimension.NETHER; - case THE_END -> Dimension.END; - default -> Dimension.OVERWORLD; - }; - } - - public String getDimensionTypeKey() { - return sanitizeDimensionTypeKeyValue(getLoadKey()); - } - - public static String sanitizeDimensionTypeKeyValue(String value) { - if (value == null || value.isBlank()) { - return "dimension"; - } - - String sanitized = value.trim().toLowerCase(Locale.ROOT).replace("\\", "/"); - sanitized = sanitized.replaceAll("[^a-z0-9_\\-./]", "_"); - sanitized = sanitized.replaceAll("/+", "/"); - sanitized = sanitized.replaceAll("^/+", ""); - sanitized = sanitized.replaceAll("/+$", ""); - if (sanitized.contains("..")) { - sanitized = sanitized.replace("..", "_"); - } - - sanitized = sanitized.replace("/", "_"); - return sanitized.isBlank() ? "dimension" : sanitized; - } - - public IrisDimensionType getDimensionType() { - IrisDimensionTypeOptions options = getDimensionOptions(); - if (fullbright) { - options = options.copy().ambientLight(1.0f); - } - return new IrisDimensionType(getBaseDimension(), options, getLogicalHeight(), getMaxHeight() - getMinHeight(), getMinHeight()); - } - - public boolean hasUpperDimension() { - return upperDimension != null && !upperDimension.isEmpty() && !upperDimension.equalsIgnoreCase("none"); - } - - public void installDimensionType(IDataFixer fixer, KList datapackRoots) throws IOException { - IrisDimensionType type = getDimensionType(); - String json = type.toJson(fixer); - String dimensionTypeKey = getDimensionTypeKey(); - - IrisLogging.debug(" Installing Data Pack Dimension Type: \"iris:" + dimensionTypeKey + '"'); - for (File datapackRoot : datapackRoots) { - File output = new File(datapackRoot, "data/iris/dimension_type/" + dimensionTypeKey + ".json"); - output.getParentFile().mkdirs(); - IO.writeAll(output, json); - } - } - - @Override - public String getFolderName() { - return "dimensions"; - } - - @Override - public String getTypeName() { - return "Dimension"; - } - - public static void writeShared( - KList datapackRoots, - DimensionHeight height, - boolean adjustVanillaHeight - ) throws IOException { - IrisLogging.debug(" Installing Data Pack Vanilla Dimension Types"); - String[] jsonStrings = height.jsonStrings(); - for (File datapackRoot : datapackRoots) { - write(datapackRoot, "overworld", jsonStrings[0], adjustVanillaHeight); - write(datapackRoot, "the_nether", jsonStrings[1], adjustVanillaHeight); - write(datapackRoot, "the_end", jsonStrings[2], adjustVanillaHeight); - } - - // Ranged formats spanning every supported runtime (26.1.2 = 101, 26.2 = 107). The bootstrap - // provisioner stages this datapack before the server (and INMS) exists, so the runtime - // version cannot be resolved there; a range keeps the emitted bytes identical on both - // install paths and both Paper versions parse ranged min_format/max_format. - int minFormat = DataVersion.minSupportedPackFormat(); - int maxFormat = DataVersion.getLatest().getPackFormat(); - String raw = """ - { - "pack": { - "description": "Iris Data Pack. This pack contains all installed Iris Packs' resources.", - "pack_format": %d, - "min_format": %d, - "max_format": %d - } - } - """.formatted(maxFormat, minFormat, maxFormat); - - for (File datapackRoot : datapackRoots) { - File mcm = new File(datapackRoot, "pack.mcmeta"); - IO.writeAll(mcm, raw); - IrisLogging.debug(" Installing Data Pack MCMeta: " + mcm.getPath()); - } - } - - private static void write(File datapackRoot, String type, String json, boolean adjustVanillaHeight) throws IOException { - if (json == null) { - return; - } - File dimTypeVanilla = new File(datapackRoot, "data/minecraft/dimension_type/" + type + ".json"); - - if (adjustVanillaHeight || dimTypeVanilla.exists()) { - dimTypeVanilla.getParentFile().mkdirs(); - IO.writeAll(dimTypeVanilla, json); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionRuntimeContract.java b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionRuntimeContract.java deleted file mode 100644 index 6b52da104..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionRuntimeContract.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.world.dimension; - -import art.arcane.iris.core.nms.datapack.DataVersion; -import art.arcane.volmlib.util.json.JSONObject; - -import java.util.Objects; - -public record IrisDimensionRuntimeContract( - String typeKey, - int minHeight, - int height, - int logicalHeight -) { - public IrisDimensionRuntimeContract { - Objects.requireNonNull(typeKey, "typeKey"); - if (typeKey.isBlank()) { - throw new IllegalArgumentException("Dimension type key cannot be blank"); - } - if (height <= 0) { - throw new IllegalArgumentException("Dimension height must be positive"); - } - if (logicalHeight < 0 || logicalHeight > height) { - throw new IllegalArgumentException("Logical height must be inside the dimension height"); - } - } - - public static IrisDimensionRuntimeContract expected(IrisDimension dimension, String namespace) { - Objects.requireNonNull(dimension, "dimension"); - Objects.requireNonNull(namespace, "namespace"); - return new IrisDimensionRuntimeContract( - namespace + ":" + dimension.getDimensionTypeKey(), - dimension.getMinHeight(), - dimension.getMaxHeight() - dimension.getMinHeight(), - dimension.getLogicalHeight()); - } - - public static void requireHotloadCompatible( - String runtimeName, - IrisDimension active, - IrisDimension replacement, - String namespace - ) { - IrisDimensionRuntimeContract actual = expected(active, namespace); - IrisDimensionRuntimeContract proposed = expected(replacement, namespace); - proposed.requireExact(runtimeName, actual); - requireGeneratedTypeCompatible(runtimeName, active, replacement); - } - - public int maxHeight() { - return Math.addExact(minHeight, height); - } - - public void requireExact(String runtimeName, IrisDimensionRuntimeContract actual) { - Objects.requireNonNull(actual, "actual"); - if (equals(actual)) { - return; - } - throw mismatch(runtimeName, actual.typeKey(), actual.minHeight(), actual.height(), actual.logicalHeight()); - } - - public void requireHeight(String runtimeName, int actualMinHeight, int actualHeight) { - if (minHeight == actualMinHeight && height == actualHeight) { - return; - } - throw mismatch(runtimeName, "unknown", actualMinHeight, actualHeight, -1); - } - - private IrisDimensionContractException mismatch( - String runtimeName, - String actualTypeKey, - int actualMinHeight, - int actualHeight, - int actualLogicalHeight - ) { - String expectedRange = minHeight + ".." + maxHeight(); - String actualRange = actualMinHeight + ".." + Math.addExact(actualMinHeight, actualHeight); - String actualLogical = actualLogicalHeight < 0 ? "unknown" : Integer.toString(actualLogicalHeight); - return new IrisDimensionContractException(runtimeName + " requires Iris dimension type " + typeKey - + " with range " + expectedRange + " and logical height " + logicalHeight - + ", but the loaded runtime uses " + actualTypeKey + " with range " + actualRange - + " and logical height " + actualLogical - + ". Generation was refused before any chunk writes. Restart after installing the exact Iris dimension type; terrain clipping is not allowed."); - } - - private static void requireGeneratedTypeCompatible( - String runtimeName, - IrisDimension active, - IrisDimension replacement - ) { - if (!Objects.equals(active.getEnvironment(), replacement.getEnvironment())) { - throw hotloadMismatch(runtimeName, active, replacement); - } - - JSONObject activeType = effectiveDimensionType(active); - JSONObject replacementType = effectiveDimensionType(replacement); - if (!replacementType.similar(activeType)) { - throw hotloadMismatch(runtimeName, active, replacement); - } - } - - private static JSONObject effectiveDimensionType(IrisDimension dimension) { - return new JSONObject(dimension.getDimensionType().toJson(DataVersion.getLatest().get())); - } - - private static IrisDimensionContractException hotloadMismatch( - String runtimeName, - IrisDimension active, - IrisDimension replacement - ) { - return new IrisDimensionContractException(runtimeName - + " cannot hotload a changed dimension environment or generated dimension type. The active environment is " - + active.getEnvironment() + " and the replacement environment is " + replacement.getEnvironment() - + ". Close and reopen Studio after changing environment, dimensionOptions, or fullbright values that alter the generated type."); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionType.java b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionType.java deleted file mode 100644 index 468eec2ac..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionType.java +++ /dev/null @@ -1,104 +0,0 @@ -package art.arcane.iris.engine.object.world.dimension; - -import art.arcane.iris.core.nms.datapack.IDataFixer; -import art.arcane.volmlib.util.data.Varint; -import art.arcane.volmlib.util.io.IO; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.NonNull; -import lombok.ToString; -import lombok.experimental.Accessors; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -@Getter -@ToString -@Accessors(fluent = true, chain = true) -@EqualsAndHashCode -public final class IrisDimensionType { - @NonNull - private final String key; - @NonNull - private final IDataFixer.Dimension base; - @NonNull - private final IrisDimensionTypeOptions options; - private final int logicalHeight; - private final int height; - private final int minY; - - public static final int MIN_HEIGHT = 16; - public static final int MAX_HEIGHT = 4064; - public static final int MIN_MIN_Y = -2032; - public static final int MAX_MIN_Y = 2031; - public static final int HEIGHT_STEP = 16; - - public IrisDimensionType( - @NonNull IDataFixer.Dimension base, - @NonNull IrisDimensionTypeOptions options, - int logicalHeight, - int height, - int minY - ) { - if (logicalHeight > height) throw new IllegalArgumentException("Logical height cannot be greater than height"); - if (logicalHeight < 0) throw new IllegalArgumentException("Logical height cannot be less than zero"); - if (height < MIN_HEIGHT || height > MAX_HEIGHT) throw new IllegalArgumentException("Height must be between 16 and 4064"); - if ((height & (HEIGHT_STEP - 1)) != 0) throw new IllegalArgumentException("Height must be a multiple of 16"); - if (minY < MIN_MIN_Y || minY > MAX_MIN_Y) throw new IllegalArgumentException("Min Y must be between -2032 and 2031"); - if ((minY & (HEIGHT_STEP - 1)) != 0) throw new IllegalArgumentException("Min Y must be a multiple of 16"); - - this.base = base; - this.options = options; - this.logicalHeight = logicalHeight; - this.height = height; - this.minY = minY; - this.key = createKey(); - } - - public static IrisDimensionType fromKey(String key) { - var stream = new ByteArrayInputStream(IO.decode(key.replace(".", "=").toUpperCase())); - try (var din = new DataInputStream(stream)) { - return new IrisDimensionType( - IDataFixer.Dimension.values()[din.readUnsignedByte()], - new IrisDimensionTypeOptions().read(din), - Varint.readUnsignedVarInt(din), - Varint.readUnsignedVarInt(din), - Varint.readSignedVarInt(din) - ); - } catch (IOException e) { - throw new RuntimeException("This is impossible", e); - } - } - - public String toJson(IDataFixer fixer) { - return fixer.createDimension( - base, - minY, - height, - logicalHeight, - options.copy() - ).toString(4); - } - - private String createKey() { - var stream = new ByteArrayOutputStream(41); - try (var dos = new DataOutputStream(stream)) { - dos.writeByte(base.ordinal()); - options.write(dos); - Varint.writeUnsignedVarInt(logicalHeight, dos); - Varint.writeUnsignedVarInt(height, dos); - Varint.writeSignedVarInt(minY, dos); - } catch (IOException e) { - throw new RuntimeException("This is impossible", e); - } - - return IO.encode(stream.toByteArray()).replace("=", ".").toLowerCase(); - } - - public IrisDimensionTypeOptions options() { - return options.copy(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionTypeOptions.java b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionTypeOptions.java deleted file mode 100644 index 875d5efa0..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionTypeOptions.java +++ /dev/null @@ -1,324 +0,0 @@ -package art.arcane.iris.engine.object.world.dimension; - -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.NonNull; -import static art.arcane.iris.engine.object.world.dimension.IrisDimensionTypeOptions.TriState.DEFAULT; -import static art.arcane.iris.engine.object.world.dimension.IrisDimensionTypeOptions.TriState.FALSE; -import static art.arcane.iris.engine.object.world.dimension.IrisDimensionTypeOptions.TriState.TRUE; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.volmlib.util.data.Varint; -import art.arcane.volmlib.util.json.JSONObject; -import lombok.experimental.Accessors; -import org.jetbrains.annotations.Nullable; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.Arrays; - - -@Data -@NoArgsConstructor -@Accessors(fluent = true, chain = true) -@Desc("Optional options for the dimension type") -public class IrisDimensionTypeOptions { - @MinNumber(0.00001) - @MaxNumber(30000000) - @Desc("The multiplier applied to coordinates when leaving the dimension. Value between 0.00001 and 30000000.0 (both inclusive).") - private double coordinateScale = -1; - @MinNumber(0) - @MaxNumber(1) - @Desc("How much light the dimension has. When set to 0, it completely follows the light level; when set to 1, there is no ambient lighting.") - private float ambientLight = -1; - @Nullable - @MinNumber(0) - @MaxNumber(Long.MAX_VALUE) - @Desc("If this is set to an int, the time of the day is the specified value. To ensure a normal time cycle, set it to null.") - private Long fixedTime = -1L; - @Nullable - @MinNumber(-2032) - @MaxNumber(2031) - @Desc("Optional value between -2032 and 2031. If set, determines the lower edge of the clouds. If set to null, clouds are disabled in the dimension.") - private Integer cloudHeight = -1; - @MinNumber(0) - @MaxNumber(15) - @Desc("Value between 0 and 15 (both inclusive). Maximum block light required when the monster spawns.") - private int monsterSpawnBlockLightLimit = -1; - - @NonNull - @Desc("Whether the dimensions behaves like the nether (water evaporates and sponges dry) or not. Also lets stalactites drip lava and causes lava to spread faster and thinner.") - private TriState ultrawarm = DEFAULT; - @NonNull - @Desc("When false, compasses spin randomly, and using a bed to set the respawn point or sleep, is disabled. When true, nether portals can spawn zombified piglins, and creaking hearts can spawn creakings.") - private TriState natural = DEFAULT; - @NonNull - @Desc("When false, Piglins and hoglins shake and transform to zombified entities.") - private TriState piglinSafe = DEFAULT; - @NonNull - @Desc("When false, the respawn anchor blows up when trying to set spawn point.") - private TriState respawnAnchorWorks = DEFAULT; - @NonNull - @Desc("When false, the bed blows up when trying to sleep.") - private TriState bedWorks = DEFAULT; - @NonNull - @Desc("Whether players with the Bad Omen effect can cause a raid.") - private TriState raids = DEFAULT; - @NonNull - @Desc("Whether the dimension has skylight or not.") - private TriState skylight = DEFAULT; - @NonNull - @Desc("Whether the dimension has a bedrock ceiling. Note that this is only a logical ceiling. It is unrelated with whether the dimension really has a block ceiling.") - private TriState ceiling = DEFAULT; - - public IrisDimensionTypeOptions( - @NonNull TriState ultrawarm, - @NonNull TriState natural, - @NonNull TriState piglinSafe, - @NonNull TriState respawnAnchorWorks, - @NonNull TriState bedWorks, - @NonNull TriState raids, - @NonNull TriState skylight, - @NonNull TriState ceiling, - double coordinateScale, - float ambientLight, - @Nullable Long fixedTime, - @Nullable Integer cloudHeight, - int monsterSpawnBlockLightLimit - ) { - if (coordinateScale != -1 && (coordinateScale < 0.00001 || coordinateScale > 30000000)) - throw new IllegalArgumentException("Coordinate scale must be between 0.00001 and 30000000"); - if (ambientLight != -1 && (ambientLight < 0 || ambientLight > 1)) - throw new IllegalArgumentException("Ambient light must be between 0 and 1"); - if (cloudHeight != null && cloudHeight != -1 && (cloudHeight < -2032 || cloudHeight > 2031)) - throw new IllegalArgumentException("Cloud height must be between -2032 and 2031"); - if (monsterSpawnBlockLightLimit != -1 && (monsterSpawnBlockLightLimit < 0 || monsterSpawnBlockLightLimit > 15)) - throw new IllegalArgumentException("Monster spawn block light limit must be between 0 and 15"); - - this.ultrawarm = ultrawarm; - this.natural = natural; - this.piglinSafe = piglinSafe; - this.respawnAnchorWorks = respawnAnchorWorks; - this.bedWorks = bedWorks; - this.raids = raids; - this.skylight = skylight; - this.ceiling = ceiling; - this.coordinateScale = coordinateScale; - this.ambientLight = ambientLight; - this.fixedTime = fixedTime; - this.cloudHeight = cloudHeight; - this.monsterSpawnBlockLightLimit = monsterSpawnBlockLightLimit; - } - - public IrisDimensionTypeOptions coordinateScale(double coordinateScale) { - if (coordinateScale != -1 && (coordinateScale < 0.00001 || coordinateScale > 30000000)) - throw new IllegalArgumentException("Coordinate scale must be between 0.00001 and 30000000"); - this.coordinateScale = coordinateScale; - return this; - } - - public IrisDimensionTypeOptions ambientLight(float ambientLight) { - if (ambientLight != -1 && (ambientLight < 0 || ambientLight > 1)) - throw new IllegalArgumentException("Ambient light must be between 0 and 1"); - this.ambientLight = ambientLight; - return this; - } - - public IrisDimensionTypeOptions cloudHeight(@Nullable Integer cloudHeight) { - if (cloudHeight != null && cloudHeight != -1 && (cloudHeight < -2032 || cloudHeight > 2031)) - throw new IllegalArgumentException("Cloud height must be between -2032 and 2031"); - this.cloudHeight = cloudHeight; - return this; - } - - public IrisDimensionTypeOptions monsterSpawnBlockLightLimit(int monsterSpawnBlockLightLimit) { - if (monsterSpawnBlockLightLimit != -1 && (monsterSpawnBlockLightLimit < 0 || monsterSpawnBlockLightLimit > 15)) - throw new IllegalArgumentException("Monster spawn block light limit must be between 0 and 15"); - this.monsterSpawnBlockLightLimit = monsterSpawnBlockLightLimit; - return this; - } - - public void write(DataOutput dos) throws IOException { - int bits = 0; - int index = 0; - - for (TriState state : new TriState[]{ - ultrawarm, - natural, - skylight, - ceiling, - piglinSafe, - bedWorks, - respawnAnchorWorks, - raids - }) { - if (state == DEFAULT) { - index++; - continue; - } - - bits |= (short) (1 << index++); - if (state == TRUE) - bits |= (short) (1 << index++); - } - - if (coordinateScale != -1) - bits |= (1 << index++); - if (ambientLight != -1) - bits |= (1 << index++); - if (monsterSpawnBlockLightLimit != -1) - bits |= (1 << index++); - if (fixedTime != null) { - bits |= (1 << index++); - if (fixedTime != -1L) - bits |= (1 << index++); - } - if (cloudHeight != null) { - bits |= (1 << index++); - if (cloudHeight != -1) - bits |= (1 << index); - } - - Varint.writeSignedVarInt(bits, dos); - - if (coordinateScale != -1) - Varint.writeUnsignedVarLong(Double.doubleToLongBits(coordinateScale), dos); - if (ambientLight != -1) - Varint.writeUnsignedVarInt(Float.floatToIntBits(ambientLight), dos); - if (monsterSpawnBlockLightLimit != -1) - Varint.writeSignedVarInt(monsterSpawnBlockLightLimit, dos); - if (fixedTime != null && fixedTime != -1L) - Varint.writeSignedVarLong(fixedTime, dos); - if (cloudHeight != null && cloudHeight != -1) - Varint.writeSignedVarInt(cloudHeight, dos); - } - - public IrisDimensionTypeOptions read(DataInput dis) throws IOException { - TriState[] states = new TriState[8]; - Arrays.fill(states, DEFAULT); - - int bits = Varint.readSignedVarInt(dis); - int index = 0; - - for (int i = 0; i < 8; i++) { - if ((bits & (1 << index++)) == 0) - continue; - states[i] = (bits & (1 << index++)) == 0 ? FALSE : TRUE; - } - ultrawarm = states[0]; - natural = states[1]; - skylight = states[2]; - ceiling = states[3]; - piglinSafe = states[4]; - bedWorks = states[5]; - respawnAnchorWorks = states[6]; - raids = states[7]; - - coordinateScale = (bits & (1 << index++)) != 0 ? Double.longBitsToDouble(Varint.readUnsignedVarLong(dis)) : -1; - ambientLight = (bits & (1 << index++)) != 0 ? Float.intBitsToFloat(Varint.readUnsignedVarInt(dis)) : -1; - monsterSpawnBlockLightLimit = (bits & (1 << index++)) != 0 ? Varint.readSignedVarInt(dis) : -1; - fixedTime = (bits & (1 << index++)) != 0 ? (bits & (1 << index)) != 0 ? Varint.readSignedVarLong(dis) : -1L : null; - cloudHeight = (bits & (1 << index++)) != 0 ? (bits & (1 << index)) != 0 ? Varint.readSignedVarInt(dis) : -1 : null; - - return this; - } - - public IrisDimensionTypeOptions resolve(IrisDimensionTypeOptions other) { - if (ultrawarm == DEFAULT) - ultrawarm = other.ultrawarm; - if (natural == DEFAULT) - natural = other.natural; - if (piglinSafe == DEFAULT) - piglinSafe = other.piglinSafe; - if (respawnAnchorWorks == DEFAULT) - respawnAnchorWorks = other.respawnAnchorWorks; - if (bedWorks == DEFAULT) - bedWorks = other.bedWorks; - if (raids == DEFAULT) - raids = other.raids; - if (skylight == DEFAULT) - skylight = other.skylight; - if (ceiling == DEFAULT) - ceiling = other.ceiling; - if (coordinateScale == -1) - coordinateScale = other.coordinateScale; - if (ambientLight == -1) - ambientLight = other.ambientLight; - if (fixedTime != null && fixedTime == -1L) - fixedTime = other.fixedTime; - if (cloudHeight != null && cloudHeight == -1) - cloudHeight = other.cloudHeight; - if (monsterSpawnBlockLightLimit == -1) - monsterSpawnBlockLightLimit = other.monsterSpawnBlockLightLimit; - return this; - } - - public JSONObject toJson() { - if (!isComplete()) throw new IllegalStateException("Cannot serialize incomplete options"); - JSONObject json = new JSONObject(); - json.put("ultrawarm", ultrawarm.bool()); - json.put("natural", natural.bool()); - json.put("piglin_safe", piglinSafe.bool()); - json.put("respawn_anchor_works", respawnAnchorWorks.bool()); - json.put("bed_works", bedWorks.bool()); - json.put("has_raids", raids.bool()); - json.put("has_skylight", skylight.bool()); - json.put("has_ceiling", ceiling.bool()); - json.put("coordinate_scale", coordinateScale); - json.put("ambient_light", ambientLight); - json.put("monster_spawn_block_light_limit", monsterSpawnBlockLightLimit); - if (fixedTime != null) json.put("fixed_time", fixedTime); - if (cloudHeight != null) json.put("cloud_height", cloudHeight); - return json; - } - - public IrisDimensionTypeOptions copy() { - return new IrisDimensionTypeOptions( - ultrawarm, - natural, - piglinSafe, - respawnAnchorWorks, - bedWorks, - raids, - skylight, - ceiling, - coordinateScale, - ambientLight, - fixedTime, - cloudHeight, - monsterSpawnBlockLightLimit - ); - } - - public boolean isComplete() { - return ultrawarm != DEFAULT - && natural != DEFAULT - && piglinSafe != DEFAULT - && respawnAnchorWorks != DEFAULT - && bedWorks != DEFAULT - && raids != DEFAULT - && skylight != DEFAULT - && ceiling != DEFAULT - && coordinateScale != -1 - && ambientLight != -1 - && monsterSpawnBlockLightLimit != -1 - && (fixedTime == null || fixedTime != -1L) - && (cloudHeight == null || cloudHeight != -1); - } - - @Desc("Allows reusing the behavior of the base dimension") - public enum TriState { - @Desc("Follow the behavior of the base dimension") - DEFAULT, - @Desc("True") - TRUE, - @Desc("False") - FALSE; - - public boolean bool() { - return this == TRUE; - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/region/IrisRegion.java b/src/main/java/art/arcane/iris/engine/object/world/region/IrisRegion.java deleted file mode 100644 index 584ace764..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/region/IrisRegion.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.world.region; - -import art.arcane.iris.engine.object.value.IRare; -import art.arcane.iris.engine.object.world.biome.InferredType; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.framework.render.RenderType; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.collection.KMap; -import art.arcane.volmlib.util.collection.KSet; -import art.arcane.iris.util.common.data.DataProvider; -import art.arcane.volmlib.util.data.VanillaBiomeColors; -import art.arcane.volmlib.util.inventorygui.RandomColor; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.util.project.noise.CNG; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.awt.Color; -import java.util.Random; - - -@Accessors(chain = true) -@NoArgsConstructor -@Desc("Represents an iris region") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisRegion extends IrisRegistrant implements IRare { - private final transient AtomicCache> cacheRidge = new AtomicCache<>(); - private final transient AtomicCache> cacheSpot = new AtomicCache<>(); - private final transient AtomicCache shoreHeightGenerator = new AtomicCache<>(); - private final transient AtomicCache> realLandBiomes = new AtomicCache<>(); - private final transient AtomicCache> realSeaBiomes = new AtomicCache<>(); - private final transient AtomicCache> realShoreBiomes = new AtomicCache<>(); - private final transient AtomicCache> realCaveBiomes = new AtomicCache<>(); - private final transient AtomicCache cacheColor = new AtomicCache<>(); - @MinNumber(2) - @Required - @Desc("The name of the region") - private String name = "A Region"; - @MinNumber(1) - @MaxNumber(128) - @Desc("The rarity of the region") - private int rarity = 1; - @MinNumber(0) - @Desc("The min shore height") - private double shoreHeightMin = 1.2; - @MinNumber(0) - @Desc("The the max shore height") - private double shoreHeightMax = 3.2; - @MinNumber(0.0001) - @Desc("The varience of the shore height") - private double shoreHeightZoom = 3.14; - @MinNumber(0.0001) - @Desc("How large land biomes are in this region") - private double landBiomeZoom = 1; - @MinNumber(0.0001) - @Desc("How large shore biomes are in this region") - private double shoreBiomeZoom = 1; - @MinNumber(0.0001) - @Desc("How large sea biomes are in this region") - private double seaBiomeZoom = 1; - @MinNumber(0.0001) - @Desc("How large cave biomes are in this region") - private double caveBiomeZoom = 1; - @RegistryListResource(IrisBiome.class) - @Required - @ArrayType(min = 1, type = String.class) - @Desc("A list of root-level biomes in this region. Don't specify child biomes of other biomes here. Just the root parents.") - private KList landBiomes = new KList<>(); - @RegistryListResource(IrisBiome.class) - @ArrayType(type = String.class) - @Desc("A list of root-level sea biomes in this region. Optional: leave empty for land-only dimensions (flat, island, or fully-land worlds where no ocean is generated). Don't specify child biomes of other biomes here. Just the root parents.") - private KList seaBiomes = new KList<>(); - @RegistryListResource(IrisBiome.class) - @ArrayType(type = String.class) - @Desc("A list of root-level shore biomes in this region. Optional: leave empty for land-only dimensions (flat, island, or fully-land worlds where no shoreline is generated). Don't specify child biomes of other biomes here. Just the root parents.") - private KList shoreBiomes = new KList<>(); - @RegistryListResource(IrisBiome.class) - @ArrayType(min = 1, type = String.class) - @Desc("A list of root-level cave biomes in this region, used for carved cave interiors. Don't specify child biomes of other biomes here. Just the root parents.") - private KList caveBiomes = new KList<>(); - @Desc("A color for visualizing this region with a color. I.e. #F13AF5. This will show up on the map.") - private String color = null; - - public String getName() { - return name; - } - - public CNG getShoreHeightGenerator() { - return shoreHeightGenerator.aquire(() -> - CNG.signature(new RNG((long) (getName().length() + getLandBiomeZoom() + getLandBiomes().size() + 3458612)))); - } - - public double getShoreHeight(double x, double z) { - return getShoreHeightGenerator().fitDouble(shoreHeightMin, shoreHeightMax, x / shoreHeightZoom, z / shoreHeightZoom); - } - - public KSet getAllBiomeIds() { - KSet names = new KSet<>(); - names.addAll(landBiomes); - names.addAll(caveBiomes); - names.addAll(seaBiomes); - names.addAll(shoreBiomes); - - return names; - } - - public KList getAllBiomes(DataProvider g) { - KMap b = new KMap<>(); - KSet names = getAllBiomeIds(); - - while (!names.isEmpty()) { - for (String i : new KList<>(names)) { - if (b.containsKey(i)) { - names.remove(i); - continue; - } - - IrisBiome biome = g.getData().getBiomeLoader().load(i); - - names.remove(i); - if (biome == null) { - continue; - } - - names.addAll(biome.getModuleSettings().treeBiomes(g.getData().getPackResources())); - b.put(biome.getLoadKey(), biome); - names.addAll(biome.getChildren()); - } - } - - return b.v(); - } - - public KList getBiomes(DataProvider g, InferredType type) { - if (type.equals(InferredType.LAND)) { - return getRealLandBiomes(g); - } else if (type.equals(InferredType.SEA)) { - return getRealSeaBiomes(g); - } else if (type.equals(InferredType.SHORE)) { - return getRealShoreBiomes(g); - } else if (type.equals(InferredType.CAVE)) { - return getRealCaveBiomes(g); - } - - return new KList<>(); - } - - public KList getRealCaveBiomes(DataProvider g) { - return realCaveBiomes.aquire(() -> - { - KList realCaveBiomes = new KList<>(); - - for (String i : getCaveBiomes()) { - realCaveBiomes.add(g.getData().getBiomeLoader().load(i)); - } - - return realCaveBiomes; - }); - } - - public KList getRealShoreBiomes(DataProvider g) { - return realShoreBiomes.aquire(() -> - { - KList realShoreBiomes = new KList<>(); - - for (String i : getShoreBiomes()) { - realShoreBiomes.add(g.getData().getBiomeLoader().load(i)); - } - - return realShoreBiomes; - }); - } - - public KList getRealSeaBiomes(DataProvider g) { - return realSeaBiomes.aquire(() -> - { - KList realSeaBiomes = new KList<>(); - - for (String i : getSeaBiomes()) { - realSeaBiomes.add(g.getData().getBiomeLoader().load(i)); - } - - return realSeaBiomes; - }); - } - - public KList getRealLandBiomes(DataProvider g) { - return realLandBiomes.aquire(() -> - { - KList realLandBiomes = new KList<>(); - - for (String i : getLandBiomes()) { - realLandBiomes.add(g.getData().getBiomeLoader().load(i)); - } - - return realLandBiomes; - }); - } - - public KList getAllAnyBiomes() { - KMap b = new KMap<>(); - KSet names = new KSet<>(); - names.addAll(landBiomes); - names.addAll(caveBiomes); - names.addAll(seaBiomes); - names.addAll(shoreBiomes); - - while (!names.isEmpty()) { - for (String i : new KList<>(names)) { - if (b.containsKey(i)) { - names.remove(i); - continue; - } - - IrisBiome biome = IrisData.loadAnyBiome(i, getLoader()); - - names.remove(i); - if (biome == null) { - continue; - } - - names.addAll(biome.getModuleSettings().treeBiomes(biome.getLoader().getPackResources())); - b.put(biome.getLoadKey(), biome); - names.addAll(biome.getChildren()); - } - } - - return b.v(); - } - - public Color getColor(DataProvider dataProvider, RenderType type) { - return this.cacheColor.aquire(() -> { - if (this.color == null) { - Random rand = new Random(getName().hashCode() + getAllBiomeIds().hashCode()); - RandomColor randomColor = new RandomColor(rand); - - KList biomes = getRealLandBiomes(dataProvider); - - while (biomes.size() > 0) { - int index = rand.nextInt(biomes.size()); - IrisBiome biome = biomes.get(index); - - String vanillaKey = biome.getVanillaDerivativeKey(); - RandomColor.Color col = vanillaKey == null ? null : VanillaBiomeColors.getColorType(vanillaKey); - if (col != null) { - RandomColor.Luminosity lum = VanillaBiomeColors.getColorLuminosity(vanillaKey); - RandomColor.SaturationType sat = VanillaBiomeColors.getColorSaturation(vanillaKey); - int newColorI = randomColor.randomColor(col, col == RandomColor.Color.MONOCHROME ? RandomColor.SaturationType.MONOCHROME : sat, lum); - return new Color(newColorI); - } - - biomes.remove(index); - } - - IrisLogging.warn("Couldn't find a suitable color for region " + getName()); - return new Color(new RandomColor(rand).randomColor()); - } - - try { - return Color.decode(this.color); - } catch (NumberFormatException e) { - IrisLogging.warn("Could not parse color \"" + this.color + "\" for region " + getName()); - return Color.WHITE; - } - }); - } - - public void pickRandomColor(DataProvider data) { - - } - - @Override - public String getFolderName() { - return "regions"; - } - - @Override - public String getTypeName() { - return "Region"; - } -}